<template>
  <div class="calendar-view">
    <div class="left-calendar">
      <div class="zuoce">
        <div class="mini-calendar-create">
          <!-- 暂时去除事件&工单 -->
          <el-button
            v-if="canBaseCalendarAdd"
            @click="createAgenda('common')"
            type="primary"
            icon="iconfont icon-add"
          >
            {{$t('calendar.createAgenda')}}</el-button
            >

            <!-- <el-dropdown placement="bottom" trigger="click">
          <base-button type="primary" icon="icon-add">新建日程</base-button>
          <el-dropdown-menu slot="dropdown" class="create-agenda-menu">
            <el-dropdown-item v-for="(item, index) in types" :key="index" style="padding: 5px 30px;font-size: 15px;">
              <div @click="createAgenda(item.type)">{{ item.name }}</div>
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown> -->
        </div>

        <div class="mini-calendar-header">
          <span class="title">{{ checkedDate }}</span>
          <i @click="pre" class="op iconfont icon-left1"></i>
          <i @click="next" class="op iconfont icon-right1"></i>
          <span @click.stop.prevent="toggleMiniWeekMonth">
            <i v-if="!isMiniMonthView" class="op iconfont icon-fdn-select"></i>
            <i v-else class="op iconfont icon-Icon_up"></i>
          </span>
        </div>

        <MiniCalendar
          ref="picker"
          model="dialog"
          week-start="sunday"
          picker-type="datetime"
          format="YY-MM-DD"
          :mark-date="markDate"
          @click="dateClick"
          @change="dateChange"
        />

        <h4>{{$t('calendar.agendaType')}}</h4>
        <div class="checkbox-group-box">
          <el-checkbox-group v-model="checkList" :min="1" class="stat-type">
            <el-checkbox class="checkbox-common" :label="$t('calendar.commonAgenda')" @change="data => calendarTypeTrack(data, 'general')"></el-checkbox>

            <div>
              <el-checkbox
                :class="{ 'checkbox-task': taskPlanningBtn == 2 }"
                :label="$t('common.base.task')"
                @change="data => calendarTypeTrack(data, 'task')"
                :disabled="taskPlanningBtn != 2"
              ></el-checkbox>
              <el-tooltip
                :content="$t('calendar.taskTips')"
                placement="top-start"
              >
                <i class="iconfont icon-bangzhu"></i>
              </el-tooltip>
            </div>

            <div>
              <el-checkbox
                :class="{ 'checkbox-event': eventPlanningBtn }"
                :label="$t('common.base.event')"
                @change="data => calendarTypeTrack(data, 'event')"
                :disabled="!eventPlanningBtn"
              ></el-checkbox>
              <el-tooltip
                :content="$t('calendar.eventTips')"
                placement="top-start"
              >
                <i class="iconfont icon-bangzhu"></i>
              </el-tooltip>
            </div>
          </el-checkbox-group>

          <div class="checkbox-type-txt">
            <div>
              <a
                href="javascript:;"
                @click="planningTimeDialog = true"
                v-if="
                  taskPlanningBtn == 0 && superAdmin == 2 && dataFlagLoading
                "
              >{{$t('calendar.openTaskAgenda')}}</a
              >
              <span
                v-if="
                  taskPlanningBtn == 0 && superAdmin != 2 && dataFlagLoading
                "
              >{{$t('calendar.contactSuperAdmin')}}</span
              >
              <span v-if="taskPlanningBtn == 1 && dataFlagLoading"
              >{{$t('calendar.openText')}}</span
              >
            </div>
            <div>
              <a
                href="javascript:;"
                @click="eventPlanningTimeDialog = true"
                v-if="!eventPlanningBtn && superAdmin == 2 && dataFlagLoading"
              >{{$t('calendar.openEventAgenda')}}</a
              >
              <span
                v-if="!eventPlanningBtn && superAdmin != 2 && dataFlagLoading"
              >{{$t('calendar.contactSuperAdmin')}}</span
              >
            </div>
          </div>
        </div>

        <h4 style="margin-top: 10px;">{{$t('calendar.viewRange')}}</h4>
        <div class="calendar-type">
          <el-radio-group v-model="calendarType" @change="checkCalendarType">
            <el-radio :label="1" :disabled="!(initData.canPersonalTaskShow && initData.canPersonalEventShow && initData.canPersonalBaseCalendarShow)">{{$t('calendar.personCalendar')}}</el-radio>
            <el-radio :label="2" v-if="(initData.canTagTaskShow && initData.canTagEventShow && initData.canTagBaseCalendarShow)">{{$t('calendar.teamCalendar')}}<span v-show="calendarType == 2" class="user-counter">{{$t('calendar.totalPerson', {length: users.length})}}</span>
            </el-radio>
          </el-radio-group>
        </div>
      
	  
	  
        <div v-show="calendarType == 2" @click="selectUser" class="calendar-tag-user">
          <span v-if="!users.length" class="placeholder-text">
            {{$t('calendar.placeHolder.statisticiansText')}}
          </span>
          <template v-else>
            <el-tag
              v-for="(item, index) in users"
              :key="item.userId"
              size='mini'
              :closable="true"
              disable-transitions
              type='info'
              @close="delUser(index)">
              <template v-if="isOpenData && item.staffId">
                <open-data :openid="item.staffId"></open-data>
              </template>
              <template v-else>
                <img :src="head(item)" alt="">
                <span>{{item.displayName}}</span>
              </template>
            </el-tag>
            <el-button v-if="users.length < 150" class="button-new-tag" icon="el-icon-plus" size="small">&nbsp;&nbsp;{{$t('calendar.detail.addPeople')}}</el-button>
          <!-- <div v-if="users.length > 1" class='biz-team-select-tags'>
            <div class='biz-team-select-tag'>+{{users.length - 1}}</div>
          </div> -->
          </template>
        </div>
        <div v-show="calendarType != 2 && fixed" class="stat-type">
          <h4>{{$t('calendar.shiftInfo')}}</h4>
          <div class="checkbox-group-box">
            <el-checkbox @change="checkPaiban" v-model="paibanList" @click.native="paibanControlClick"
            >{{$t('calendar.showShiftInfo')}}</el-checkbox
            >
            <el-tooltip placement="top-start">
              <div
                slot="content"
                v-if="ban.voList && ban.voList[0] && ban.voList[0].workNameList"
              >
                <p
                  v-for="(item, i) in ban.voList[0].workNameList"
                  :key="item.id"
                  :style="{ 'margin-top': i != 0 ? '10px' : '' }"
                  style="margin-bottom:0"
                >
                  {{ getShiftName(item.name) }}
                  <span
                    v-for="i in item.baseWorkNameTimeParamList"
                    :key="i.id"
                    style="margin-left: 10px;"
                  >{{ i.startTime }}-{{ i.endTime }}</span
                  >
                </p>
              </div>
              <i class="iconfont icon-bangzhu"></i>
            </el-tooltip>
          </div>
        </div>
        <div class="shiyong">
          <div @click="used" v-track="$track.formatParams('HOW_TO_USE')">{{$t('calendar.howUse')}}</div>
        </div>
      </div>
    </div>

    <div class="right-calendar" v-loading="loading">
      <div class="top-content" :class="isShowShadow && 'showShadow'">
        <div class="left">
          <el-button @click="todayFn" class="today-btn" :disabled="isToday"
          >{{$t('common.base.today')}}</el-button
          >
          <span>{{ currentDateStr }}</span>
          <span
            class="banci"
            style="margin-left:10px"
            v-if="paibanList && paiban.workName"
            :style="{ background: paiban.colour }"
          >{{ paiban.workName ? paiban.workName.substr(0, 1) : '' }}</span
          >
          <i @click="prevFn" class="op iconfont icon-left1"></i>
          <i @click="nextFn" class="op iconfont icon-right1"></i>
        </div>
        <div class="right">
          <el-radio-group v-model="viewType" @change="changeViewTypeFn($event, 'handle')">
            <el-radio-button
              :label="
                calendarType !== 2 ? 'timeGridDay' : 'resourceTimelineDay'
              "
            >{{$t('common.time.day1')}}</el-radio-button
            >
            <el-radio-button
              :label="
                calendarType !== 2 ? 'timeGridWeek' : 'resourceTimelineWeek'
              "
            >{{$t('common.time.week')}}</el-radio-button
            >
            <el-radio-button v-if="calendarType !== 2" label="dayGridMonth"
            >{{$t('common.time.month')}}</el-radio-button
            >
            <!-- <el-radio-button label="listWeek">列表</el-radio-button> -->
          </el-radio-group>
        </div>
      </div>
      <FullCalendar
        id="calendar"
        ref="calendarRef"
        :options="calendarOptions"
      ></FullCalendar>
    </div>

    <!-- 创建通用日程 -->
    <agenda-dialog
      :start-time="startTime"
      :end-time="endTime"
      :plan-time-config="calendarOptions.planTimeConfig"
      :agenda-info="agendaInfo"
      ref="agendaDialogRef"
      @submit="submit"
    >
    </agenda-dialog>

    <!-- 创建工单日程 -->
    <agendar-task-dailog
      :select-date="selectDate"
      :agenda-info="agendaInfo"
      :task-start-time="taskStartTime"
      :task-end-time="taskEndTime"
      :can-base-calendar-add-user="initData.canBaseCalendarAddUser"
      :plan-time-config="calendarOptions.planTimeConfig"
      ref="agendaTaskDialogRef"
      @reset="() => (taskStartTime = '')"
      @submitCreateTask="createTaskAgenda"
    >
    </agendar-task-dailog>

    <!-- 创建事件日程 -->
    <agendar-event-dailog
      :select-date="selectDate"
      :agenda-info="agendaInfo"
      :event-start-time="eventStartTime"
      :event-end-time="eventEndTime"
      :plan-time-config="calendarOptions.planTimeConfig"
      ref="agendaEventDialogRef"
      @submitCreateEvent="createEventAgenda"
    >
    </agendar-event-dailog>

    <!-- 通用日程详情 -->
    <agenda-detail
      :agenda-id="agendaId"
      ref="agendaDetailRef"
      @edit="edit"
      @cancel="cancel"
      @del="del"
    >
    </agenda-detail>

    <!-- 工单日程详情 -->
    <agenda-task-detail
      :task-id="taskId"
      ref="agendaTaskDetailRef"
      @del="deleteTask"
    >
    </agenda-task-detail>

    <!-- 事件日程详情 -->
    <agenda-event-detail
      :event-id="eventId"
      ref="agendaEventDetailRef"
      @del="deleteEvent"
    >
    </agenda-event-detail>

    <!-- start 工单发起审批弹窗 -->
    <propose-approve-dialog ref="proposeApprove" />
    <!-- end 工单发起审批弹窗 -->

    <!-- start 日程管理需求-日程初始化设置提醒 -->
    <el-dialog
      :title="$t('calendar.openTaskAgenda')"
      class="planningTimePop"
      :visible.sync="planningTimeDialog"
      width="672px"
    >
      <div class="pop_main">
        <div>
          <p>
            {{$t('calendar.taskAgendaText')}}<i>”{{$t('common.form.type.planTime')}}“</i>{{$t('calendar.modifiedAs')}}：
            <el-radio-group v-model="planTimeTypeCode">
              <el-radio :label="1">{{$t('common.form.type.planStartTime')}}</el-radio>
              <el-radio :label="2">{{$t('common.form.type.planEndTime')}}</el-radio>
            </el-radio-group>
          </p>
          <p>
            系统将于晚上
            0点，对字段进行更新，预计30分钟内完成，届时请确保系统无人使用。
          </p>
        </div>

        <div>
          {{$t('calendar.operateInstructions')}}：<br />
          1、<i>{{$t('common.form.type.planTime')}}</i>{{$t('calendar.modifyIrreversible')}}<br />
          2、<i>{{$t('common.form.type.planTime')}}</i>{{$t('calendar.modifyText')}}<a
            :href="tenantType == 4 ? 'https://publink-hz.feishu.cn/wiki/wikcntWqJF85QGKpNUZj9anhwYd' : 'https://doc.shb.ltd/shb_xoqazk/ia4qctp2ly559d1m/ahygw4zxn6uqlole/sgsegswcm1n3pnyt.html'"
          >{{$t('calendar.helpDoc')}}</a
          >
          。
        </div>

        <el-checkbox v-model="planTimeTypeCheckbox"
        >{{$t('calendar.knowImpact')}}</el-checkbox
        >
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="planningTimeDialog = false">{{$t('common.base.cancel')}}</el-button>
        <base-button
          type="primary"
          @event="planningTime"
          :disabled="planTimeTypeCode && planTimeTypeCheckbox ? false : true"
        >{{$t('common.base.confirm')}}</base-button
        >
      </div>
    </el-dialog>
    <!-- end 日程管理需求-日程初始化设置提醒 -->

    <!-- start 开通事件 -->
    <el-dialog
      :title="$t('calendar.openEventAgenda')"
      class="planningTimePop"
      :visible.sync="eventPlanningTimeDialog"
      width="472px"
    >
      <div class="pop_main">
        {{$t('calendar.afterOpenText')}}<br />
        {{$t('calendar.boardShow')}}
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="eventPlanningTimeDialog = false">{{$t('common.base.cancel')}}</el-button>
        <base-button type="primary" @event="openEvent">{{$t('common.base.confirm')}}</base-button>
      </div>
    </el-dialog>
    <!-- end 开通事件 -->
    <!-- 引导视频-->
    <GuidanceDialog
      :title="guideSetting.title"
      :steps="guideSetting.steps"
      :more-url="guideSetting.moreUrl"
      ref="GuidanceDialog"
    />
  </div>
</template>

<script>
import { getRootWindowInitData } from '@src/util/window'
import { isAllotByDepartment, isOpenData, openAccurateTab } from '@src/util/platform';
import AuthUtil from '@src/util/auth';
import * as EventApi from '@src/api/EventApi.js';
import * as TaskApi from '@src/api/TaskApi.ts';
import * as CalendarApi from '@src/api/CalendarApi.ts';
import {
  getCalendarUser,
  postSettingPlanTime,
  getSettingCalendar,
} from '@src/api/SettingApi.ts';
import { getSelectDepartmentCalendarUserList } from '@src/component/common/BaseSelectUser/api'
import { getOssUrl } from '@src/util/assets'
const defaultAvatar = getOssUrl('/avatar.png')
import '@fullcalendar/core/vdom' // vite下有问题所以这样引入
import FullCalendar from '@fullcalendar/vue';
import dayGridPlugin from '@fullcalendar/daygrid';
import timeGridPlugin from '@fullcalendar/timegrid';
import listPlugin from '@fullcalendar/list';
import interactionPlugin from '@fullcalendar/interaction';
import resourceTimeGridPlugin from '@fullcalendar/resource-timegrid';
import resourceTimelinePlugin from '@fullcalendar/resource-timeline';
import MiniCalendar from './components/mini-calendar';
import AgendaDialog from './components/AgendaDialog';
import AgendaDetail from './components/AgendaDetail';
import AgendaTaskDetail from './components/AgendaTaskDetail';
import AgendaEventDetail from './components/AgendaEventDetail';
import ProposeApproveDialog from '@src/modules/task/view/components/ProposeApproveDialog.vue';
import GuidanceDialog from '@src/modules/setting/productV2/productSet/components/GuidanceDialog.vue';
import { formatDate, getPlanStartTime, getPlanEndTime, getTimestamp, dayTimeStart, dayTimeEnd } from 'pub-bbx-utils';
import lunar from './lunar';
import Popper from 'popper.js';
import * as dom from '@src/util/dom';
import { parse } from '@src/util/querystring';
import { BaseSelectUserModeEnum } from '@src/component/common/BaseSelectUser/model/enum'

import tippy from 'tippy.js';
import 'tippy.js/dist/tippy.css';
let el, popper, selectStartTime, selectEndTime;
let query = parse(window.location.search) || {};

import { storageGet, storageSet, storageRemove } from '@src/util/storageV2';
import { safeNewDate } from '@src/util/time';
import { getThemeColor } from '@src/util/business/color'

let currentDay = safeNewDate().getDate();
let currentMonth = safeNewDate().getMonth() + 1;
let currentYear = safeNewDate().getFullYear();

const typeMap = {
  工单: 2,
  事件: 1,
  通用日程: 3,
};
const CALENDAR_QUERY_CONDITIONS_KEY = 'calendar_query_conditions'
let calendarApi;
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import i18n, { t } from '@src/locales'
import allLocales from '@fullcalendar/core/locales-all';
const shiftName = {
  '默认班次': t('calendar.defaultShift'),
}
const shbLocale = i18n.locale
export default {
  components: {
    FullCalendar,
    MiniCalendar,
    AgendaDialog,
    GuidanceDialog,
    AgendaDetail,
    AgendaTaskDetail,
    AgendaEventDetail,
    ProposeApproveDialog,
  },
  inject: ['initData'],
  data() {
    return {
      openTaskTime:'',
      guideSetting: {
        title: this.$t('calendar.calendarGuild'),
        moreUrl: this.tenantType == 4 ? 'https://publink-hz.feishu.cn/wiki/wikcntWqJF85QGKpNUZj9anhwYd' : 'https://doc.shb.ltd/shb_xoqazk/ia4qctp2ly559d1m/ahygw4zxn6uqlole/sgsegswcm1n3pnyt.html',
        steps: [
          {
            type: 'video',
            url:
              'https://file.shb.ltd/shb-resource/shb-calendar/%E6%97%A5%E7%A8%8B%E7%AE%A1%E7%90%86%E8%A7%86%E9%A2%91%201.mp4',
            text:
              this.$t('calendar.videoText1'),
          },
          {
            type: 'video',
            url:
              'https://file.shb.ltd/shb-resource/shb-calendar/%E6%97%A5%E7%A8%8B%E7%AE%A1%E7%90%86%E8%A7%86%E9%A2%91%202.mp4',
            text:
              this.$t('calendar.videoText2'),
          },
          {
            type: 'video',
            url:
              'https://file.shb.ltd/shb-resource/shb-calendar/%E6%97%A5%E7%A8%8B%E7%AE%A1%E7%90%86%E8%A7%86%E9%A2%91%203.mp4',
            text:
              this.$t('calendar.videoText3'),
          },
        ],
      },
      // ,
      //           {
      //             type: 'video',
      //             url: 'https://file.shb.ltd/shb-resource/shb-calendar/%E6%97%A5%E7%A8%8B%E7%AE%A1%E7%90%86%E8%A7%86%E9%A2%91%204.mp4',
      //             text: '查看日程，系统提供mini日历、日程类型筛选、个人/团队日历、多种视图类型（日视图、周视图、月视图）方便用户查看自己的工作安排；',
      //           }
      scrollHeight: '', // 滑动高度

      isOpenData,
      loading: false,

      isToday: true,
      dialogVisible: false,

      users: [],
      checkedDate: '',
      markDate: [],

      checkList: [],
      calendarType: 1,

      selectDate: '',
      agendaId: '',
      taskId: '',
      eventId: '',
      agendaType: '',

      startTime: '',
      endTime: '',
      taskStartTime: '',
      taskEndTime: '',
      eventStartTime: '',
      eventEndTime: '',
      agendaInfo: {},
      showDetail: false,
      currentDateStr: '',
      currentWeekStart: '',
      currentWeekend: '',
      viewType: 'timeGridDay', // 显示方式
      idSortSourses: false,
      // 日历配置项
      calendarOptions: {
        // locale: 'zh-cn', // 中文
        locales: allLocales,
        height: '100%',
        // contentHeight: 'auto',
        // handleWindowResize: true,
        plugins: [
          dayGridPlugin,
          timeGridPlugin,
          interactionPlugin,
          listPlugin,
          resourceTimeGridPlugin,
          resourceTimelinePlugin,
        ],
        resourceAreaHeaderContent: ' ',
        stickyHeaderDates: true,
        // stickyFooterScrollbar: true,
        nowIndicator: true,
        loading(isLoading, view) {
          // 视图数据加载中、加载完成触发
          if (isLoading == false) {
            let timeline = document.querySelectorAll(
              '.fc-timegrid-now-indicator-line'
            );
            if (
              timeline
              && timeline.length !== 0
              && !timeline[0].classList.contains(
                'fc-timegrid-now-indicator-line-main'
              )
            ) {
              let fistTimeLine = timeline[0];
              fistTimeLine.innerHTML = '<div class="fc-timegrid-now-indicator-arrow-main"></div><div class="fc-timegrid-now-indicator-line-main"></div>';
            }
          }
        },

        // 时间轴间距
        // slotMinTime: '00:00',
        // slotMaxTime: '23:00',
        // slotDuration: '00:15:00',
        // defaultTimedEventDuration: '00:30',
        // 是否显示全天插槽
        allDaySlot: true,
        allDayText: this.$t('calendar.crossDay'),
        initialDate: safeNewDate(),
        initialView: 'timeGridDay',
        resources: [],
        resourceOrder: 'index', // resources是根据什么去排序的
        viewDidMount: info => {
          // console.info('viewDidMount', info)
        },
        headerToolbar: {
          center: 'title',
        },
        titleFormat: {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
        },
        // timeGridEventMinHeight: '20', // 设置事件的最小高度
        aspectRatio: 1.65, // 设置日历单元格宽度与高度的比例
        // expandRows: true,
        // dayMaxEventRows: true, // ???
        slotEventOverlap: false, // 相同时间段的多个日程视觉上是否允许重叠，默认true允许
        slotDuration: '00:30:00',
        resourceAreaWidth: '104px', // 左边resources的宽度
        slotLabelFormat: {
          hour: '2-digit',
          minute: '2-digit',
          meridiem: false,
          hour12: false, // 设置时间为24小时
        },
        timeFormat: { agenda: 'H:mm{-H:mm}', month: 'H:mm' }, // 日程的时间显示格式
        scrollTime: this.handleScrollTime(),
        maxTime: '00:00:00',
        minTime: '23:00:00',
        views: {
          dayGridMonth: {
            // 转农历
            dayCellContent(item) {
              let date = safeNewDate(item.date).toLocaleDateString().split('/');
              const {
                festival,
                lunarFestival,
                Term,
                IDayCn,
              } = lunar.solar2lunar(date[0], date[1], date[2]);
              const f = festival || lunarFestival || Term || IDayCn;
              if(currentYear == date[0] && currentMonth == date[1] && currentDay == date[2]) {
                if(shbLocale == 'zh') {
                  return {html:`<span class="current-month-day">${date[2]}</span><span style="padding: 4px;font-size: 12px;">${f}</span>`}
                }else {
                  return {html:`<span class="current-month-day">${date[2]}</span>`}
                }
              }
              if(shbLocale == 'zh') {
                return {
                  html: `<span style="padding: 4px;color: #595959;">${
                    date[2]
                  }</span><span style="padding: 4px;font-size: 12px;color: #8c8c8c;">${f}</span>`,
                };
              }else {
                return {
                  html: `<span style="padding: 4px;color: #595959;">${date[2]}</span>`,
                };
              }
            },
          },
          // timeGrid: {
          //   dayMaxEventRows: 6 // adjust to 6 only for timeGridWeek/timeGridDay
          // }
        },

        noEventsContent: this.$t('calendar.noChange'),
        editable: false,
        selectable: false,
        selectMirror: true,
        dayMaxEvents: true,
        dateClick: this.handleDateClick, // 点击某一天 // 想要触发dateClick事件必须先安装引用interaction插件
        select: this.handleDateSelect,
        eventClick: this.handleEventClick,
        moreLinkClick: this.handleMoreLinkClick,
        moreLinkDidMount: this.handleMoreLinkDidMount,
        moreLinkContent: this.handleMoreLinkContent,
        eventsSet: this.handleEvents,
        events: [],
        eventColor: getThemeColor(), // 修改日程背景色
        eventDidMount: this.eventDidMount,
        eventWillUnmount: this.eventWillUnmount,
        planTimeConfig: 60,
        // displayEventTime: false,
        displayEventEnd: false, // 不显示结束时间
        eventTimeFormat: {
          // like '14:30'
          hour: '2-digit',
          minute: '2-digit',
          meridiem: false,
          hour12: false, // 设置时间为24小时
        },
        eventMouseEnter: this.handleEventMouse,
      },
      currentEvents: [],
      dateChangeFlag: false,
      isMiniMonthView: true,

      taskPlanningBtn: null,
      planningTimeDialog: false,
      planTimeTypeCode: '',
      planTimeTypeCheckbox: false,

      eventPlanningTimeDialog: false,
      eventPlanningBtn: false,

      superAdmin: '',
      calendarData: [],
      dataFlagLoading: false,
      paibanList:false,
      fixed: false,
      ban: {},
      paiban: {},
      calendarQueryConditions: {
        checkList: [], // 日程类型
        calendarType: 1, // 查看返回 个人日历（1）团队日历（2）
        paibanList: false, // 班次信息
        viewType: 'timeGridDay', // 日周月
        users: [], // 团队日历选择的用户
      },
      cacheCheckListEnable: false,
      cacheCalendarEnable: false,
      cacheUserEnable: false,
      cacheViewTypeEnable: false,
      cachePaibanEnable: false,
      viewTypeMap: {
        'timeGridDay': this.$t('common.time.day1'),
        'timeGridWeek': this.$t('common.time.week'),
        'dayGridMonth': this.$t('common.time.month'),
        'resourceTimelineDay': this.$t('common.time.day1'),
        'resourceTimelineWeek': this.$t('common.time.week'),
      }
    };
  },
  computed: {
    tenantType() {
      return getRootWindowInitData()?.tenantType;
    },
    authorities() {
      return this.initData.auth || {};
    },
    canBaseCalendarAdd() {
      return this.initData.canBaseCalendarAdd || false;
    },
    allowCreateTask() {
      return AuthUtil.hasAuth(this.authorities, 'TASK_ADD');
    },
    allowCreateEvent() {
      return AuthUtil.hasAuth(this.authorities, 'CASE_ADD');
    },
    allowCreateAgenda() {
      return AuthUtil.hasAuth(this.authorities, 'CALENDAR_ADD');
    },
    types() {
      // [{type:'task', name:'工单日程'}, {type:'event', name: '事件日程'}, {type:'common', name: '通用日程'}]
      let arr = [];
      if (this.allowCreateTask) {
        arr.push({ type: 'task', name: this.$t('calendar.taskAgenda') });
      }
      if (this.allowCreateEvent) {
        arr.push({ type: 'event', name: this.$t('calendar.eventAgenda') });
      }
      if (this.allowCreateAgenda) {
        arr.push({ type: 'common', name: this.$t('calendar.commonAgenda') });
      }
      return arr;
    },
    taskTypeList() {
      return this.initData.taskTypeList || [];
    },
    eventTypeList() {
      return this.initData.eventTypeList || [];
    },
    // 判断是否钉钉端
    tenantType() {
      let tenantType = localStorage.getItem('tenantType') || '';
      return tenantType == 0;
    },
    // 是否是团队 & 天
    isTeamDay() {
      return this.calendarType == 2;
    },
    // 是否是团队 & 天
    isShowShadow() {
      return (
        this.scrollHeight > 20
        && this.calendarOptions.resources.length <= 0
        && this.viewType == 'timeGridDay'
        && !this.calendarOptions.allDaySlot
      );
    },
  },
  watch: {
    viewType: {
      handler(val) {
        this.calendarQueryConditions.viewType = val;
        if (val === 'resourceTimelineWeek') {
          this.calendarOptions.slotDuration = '24:00:00';
          this.calendarOptions.slotLabelFormat = {
            weekday: 'short',
            month: 'numeric',
            day: 'numeric',
            meridiem: false,
          };
        } else if (val === 'resourceTimelineDay') {
          this.calendarOptions.slotDuration = '01:00:00';
          this.calendarOptions.slotMinWidth = '60';
          this.calendarOptions.slotLabelFormat = {
            hour: '2-digit',
            minute: '2-digit',
            meridiem: false,
            hour12: false, // 设置时间为24小时
          };
        } else {
          this.calendarOptions.slotDuration = '00:30:00';
          this.calendarOptions.slotLabelFormat = {
            hour: '2-digit',
            minute: '2-digit',
            meridiem: false,
            hour12: false, // 设置时间为24小时
          };
        }
        if(this.cacheViewTypeEnable) {
          this.cacheViewTypeEnable = false;
          return;
        }
        storageSet(CALENDAR_QUERY_CONDITIONS_KEY, JSON.stringify(this.calendarQueryConditions));
      },
    },
    checkList: {
      handler() {
        this.calendarQueryConditions.checkList = this.checkList;
        if(this.cacheCheckListEnable) {
          this.cacheCheckListEnable = false;
          return;
        }
        storageSet(CALENDAR_QUERY_CONDITIONS_KEY, JSON.stringify(this.calendarQueryConditions));
        this.getAgendaCalendar();
      },
    },
    calendarType: {
      handler(nv) {
        if (nv == 1) {
          this.calendarOptions.selectable = true;
          this.viewType = 'timeGridDay';
          this.calendarOptions.eventMaxStack = 10000;
        } else {
          if(!this.cacheCalendarEnable){
            this.viewType = 'resourceTimelineDay';
          }
          this.calendarOptions.selectable = this.canBaseCalendarAdd;
          this.calendarOptions.eventMaxStack = 4;
        }
        this.calendarQueryConditions.calendarType = this.calendarType;
        if(this.cacheCalendarEnable) {
          this.cacheCalendarEnable = false;
          return;
        }
        storageSet(CALENDAR_QUERY_CONDITIONS_KEY, JSON.stringify(this.calendarQueryConditions));
        this.changeViewTypeFn(this.viewType);

        // this.getAgendaCalendar();
      },
    },
    users: {
      handler() {
        this.calendarQueryConditions.users = this.users;
        if(this.cacheUserEnable) {
          this.cacheUserEnable = false;
          return;
        }
        storageSet(CALENDAR_QUERY_CONDITIONS_KEY, JSON.stringify(this.calendarQueryConditions));
        if (this.idSortSourses) {
          this.idSortSourses = false;
          return;
        }
        if(this.calendarType === 2) { // 只有团队日历才调用
          this.getAgendaCalendar();
        }
      },
    },
    paibanList: {
      handler() {
        this.calendarQueryConditions.paibanList = this.paibanList;
        if(this.cachePaibanEnable) {
          this.cachePaibanEnable = false;
          return;
        }
        storageSet(CALENDAR_QUERY_CONDITIONS_KEY, JSON.stringify(this.calendarQueryConditions));
      }
    }
  },
  async mounted() {
    this.superAdmin = localStorage.getItem('superAdmin');
    
    this.calendarOptions.locale =  shbLocale;
    /** * 日程管理需求-日程初始化设置提醒 */
    try {
      await this.getTaskPlanFlag();
      await this.getEventPlanFlag();

      this.dataFlagLoading = true;
    } catch (error) {
      this.dataFlagLoading = true;
      console.warn(error);
    }
    const { id, startTime, endTime, type: calendarType } = query;
    if (id && startTime && endTime) {
      // 从消息中心跳转过来的打开,不能传开始时间和结束时间，因为此时的时间是错误的
      // 这里还可能是从点击首页顶部今日日程打开对应日程详情 
      // calendarType 1是事件 2是工单
      this.agendaId = id;
      let timeInfo = {
        start: parseInt(startTime),
        end: parseInt(endTime),
        agendaId: this.agendaId || '',
        notificationEnable: true,
      };
      if(calendarType == 1) {
        // 打开事件详情
        this.$refs.agendaEventDetailRef.showDetail(id);
      } else if(calendarType == 2) {
        // 打开工单详情
        this.$refs.agendaTaskDetailRef.showDetail(id);
      } else {
        this.agendaType = 3;
        this.$refs.agendaDetailRef.showDetail(timeInfo);
      }
    }

    /* this.$nextTick(() => {
      calendarApi = this.$refs.calendarRef.getApi();
      this.currentDateStr = this.dateFormat(calendarApi.getDate());
      // this.getCurrentWeekTime(calendarApi.getDate());
      // this.getAgendaCalendar();
      this.getScrollHeight();
      this.rili();
    });*/
    document.addEventListener('click', this.isInCalendar, false);
    // this.getAgendaConfig()

    window.__exports__refresh = () => {
      return new Promise((resolve, reject) => {
        this.fromUserCard();
        this.refresh(true);
        resolve();
      });
    };
    if (!localStorage.getItem('calendermp4')) {
      this.openGuidanceDialog();
    }
    await this.getFixed()
    this.$nextTick(()=>{
	    calendarApi = this.$refs.calendarRef.getApi()
	    // this.getCurrentWeekTime(calendarApi.getDate());
	    // this.getAgendaCalendar();
      // 人员卡片跳转过来
      let userCardEnable = this.fromUserCard();
      // 缓存
      let queryConditions = storageGet(CALENDAR_QUERY_CONDITIONS_KEY) && JSON.parse(storageGet(CALENDAR_QUERY_CONDITIONS_KEY));
      if(queryConditions && !userCardEnable) {
        // 日程类型
        if(queryConditions.checkList && queryConditions.checkList.length !== 0) {
          this.checkList = queryConditions.checkList.filter((item) => {
            // 权限判断
            return (this.taskPlanningBtn == 2 && item === this.$t('common.base.task')) || (this.eventPlanningBtn && item === this.$t('common.base.event')) || (item === this.$t('calendar.commonAgenda'))
          })
          this.cacheCheckListEnable = true;
        }
        // 查看返回
        if(queryConditions.calendarType !== -1) {
          this.calendarType = queryConditions.calendarType;
          if(this.calendarType === 2) { // 团队日历
            this.users = queryConditions.users;
            this.cacheCalendarEnable = true;
            this.cacheUserEnable = true;
          }
        }
        if(queryConditions.viewType) {
          this.viewType = queryConditions.viewType;
          calendarApi.changeView(this.viewType);
          this.cacheViewTypeEnable = true;
        }
        this.paibanList = queryConditions.paibanList;
        this.cachePaibanEnable = true;
      }else {
        if (this.taskPlanningBtn == 2) {
          this.checkList.push(this.$t('common.base.task'));
        }
        if (this.eventPlanningBtn) {
          this.checkList.push(this.$t('common.base.event'));
        }
        this.checkList.push(this.$t('calendar.commonAgenda'));
      }
      this.currentDateStr = this.dateFormat(calendarApi.getDate())
	    this.getScrollHeight();
	    this.rili()
    })
    try {
      // 日历没有刷新出来时需要刷新一下
      let currentIframe = top.document.getElementById('tab_M_CALENDAR_ALL')
      currentIframe.addEventListener('click', () => {
        let bodyWidth = document.getElementsByClassName('fc-timegrid-body');
        if(bodyWidth && bodyWidth.length !== 0 && bodyWidth[0].style && bodyWidth[0].style.width == '0px') {
          this.refresh(true);
        }
      })
    } catch (error) {}

    function viewEvent(sessionKey = ''){
      const event = JSON.parse(localStorage.getItem(sessionKey) ?? 'null')
      if(!event) return console.warn(`未找到sessionKey: ${sessionKey} 对应`)
      const calendarClickInfo = {
        event
      };
      this.$nextTick(() => {
        this.handleEventClick(calendarClickInfo)
      })
    }

    const { type, sessionKey, calendarId } = query;
    switch (type) {
    case 'create':
      this.createAgenda('common');
      break;
    case 'edit':
      this.edit(calendarId); // 编辑日程跳转地址：‘/calendar?type=edit&calendarId=${id}’
      break;
    case 'view':
      viewEvent(sessionKey)
      break;
    default:
    }
  },
  methods: {
    calendarTypeTrack(data, type) {
      const secondTrackIdObj = {
        general: 'SCHEDULE_TYPE_SWITCH_GENERAL',
        task: 'SCHEDULE_TYPE_SWITCH_TASK',
        event: 'SCHEDULE_TYPE_SWITCH_EVENT'
      }
      this.$track.clickStat(this.$track.formatParams('SCHEDULE_TYPE_SWITCH', data ? 'CHECKED' : 'NOT_CHECKED', secondTrackIdObj[type]));
    },
    getShiftName(item) {
      return shiftName[item] || item
    },
    fromUserCard() {
      let userCardEnable = false;
      try{
        if(localStorage.getItem('calendarTeam')){
          userCardEnable = true;
          storageRemove(CALENDAR_QUERY_CONDITIONS_KEY)
          this.calendarType = 2
          this.users = JSON.parse(localStorage.getItem('calendarTeam'));
          this.users = this.users.map((item, index) => {
            return { ...item, index };
          });
          this.viewType = 'resourceTimelineDay';
          calendarApi.changeView(this.viewType);
          this.cacheViewTypeEnable = true;
          this.cacheCalendarEnable = true;
          this.cacheUserEnable = true;
          localStorage.removeItem('calendarTeam')
        }
      }catch(error){
        console.warn(error);
      }
      return userCardEnable;
    },
	 async getFixed(){
		 try{
			 let res = await CalendarApi.getFixed()
			 if(res.status != 0) this.$platform.alert(res.message);
			 this.fixed = res.data
		 } catch(error){
			 console.log(error)
		 }
	  },
    checkCalendarType(val){
      if(val == 1){
        this.checkPaiban(true)
      }else{
        this.paibanList = false
        this.checkPaiban(false)
        if(this.users.length) {
          this.$track.clickStat(this.$track.formatParams('CHECK_GROUP_CALENDAR', this.users.length));
        }
      }
    },
	  checkPaiban(val){
		  this.setRili(val)
	  },
    paibanControlClick(e) {
      // 避免同时触发两次
      if(e.target.tagName === 'INPUT') return
      this.$track.clickStat(this.$track.formatParams('DISPLAY_SHIFT_INFORMATION', !this.paibanList ? 'CHECKED' : 'NOT_CHECKED'));
    },
	  async rili(){
		  try{
			  let obj = {}
			  if(this.viewType == 'timeGridWeek'){
				  let arr = calendarApi ? calendarApi.currentData.viewTitle.split(' – ') : ''
				  if(arr){
            obj.startTime = safeNewDate(arr[0]).getTime()
            obj.endTime = safeNewDate(arr[1]).getTime()
				  }
			  }else if(this.viewType == 'dayGridMonth'){
				  let arr = calendarApi ? calendarApi.currentData.viewTitle.split(' – ') : ''
				  if(arr){
            obj.startTime = safeNewDate(arr[0]).getTime()
            obj.endTime = safeNewDate(arr[1]).getTime()
				  }
			  }else{
				  let arr = calendarApi ? calendarApi.currentData.viewTitle : ''
				  obj.startTime = safeNewDate(arr).getTime()
				  obj.endTime = safeNewDate(arr).getTime()
			  }
			  obj.time = calendarApi.currentData.viewTitle;
			  if(this.fixed){
				  let res = await CalendarApi.queryByUserId(obj)
				  if(res.status != 0) this.$platform.alert(res.message);
				  this.ban = res.data;
			  }
			  this.setRili()
		  }catch(error){
			  console.log(error)
		  }
	  },
	  getHtml(item){
		  let _this = this
		  let ban = {}, bu = '';
		  if (_this.ban.voList && _this.ban.voList.length && _this.ban.voList[0].workSchedulingVoList && _this.ban.voList[0].workSchedulingVoList.length) {
		  	_this.ban.voList[0].workSchedulingVoList.forEach(i => {
		  		let day = safeNewDate(i.date).getDate();
          let Month = safeNewDate(i.date).getMonth() + 1;
		  		if(safeNewDate(item.date).getDate() == day && safeNewDate(item.date).getMonth() + 1 == Month){
		  			ban = i
		  		}
		  	});
		  }
		  if (_this.ban.sumNumberVoList && _this.ban.sumNumberVoList.length) {
		  	_this.ban.sumNumberVoList.forEach(o => {
		  		let day = safeNewDate(o.time).getDate();
          let Month = safeNewDate(o.time).getMonth() + 1;
		  		if(safeNewDate(item.date).getDate() == day && safeNewDate(item.date).getMonth() + 1 == Month){
		  			bu = o
		  		}
		  	});
		  }
		  
		  let buHtml = `<span class=${bu.type == 0 ? 'xiu' : 'ban'}>${bu.type == 0 ? this.$t('calendar.rest') : bu.type == 1 ? this.$t('calendar.duty') : ''}</span>`
		  let dev = `${((bu.type == 0 || bu.type == 1) && this.calendarType === 1) ? buHtml : ''}<span class="banci" style="background:${ban ? ban.colour : '#fff'}">${ban && ban.workName ? ban.workName.substr(0, 1) : ''}</span>`
		  return dev
    },
    setRili(){
      let _this = this;
      let val = this.paibanList;
      if(this.viewType == 'timeGridWeek'){
        this.calendarOptions.views.timeGridWeek = {
          dayHeaderContent(item){
            let dev = _this.getHtml(item);
            return { html: `${item.text}${val ? dev : ''}` };

          },
        };
      }else if(this.viewType == 'dayGridMonth'){
        this.calendarOptions.views.dayGridMonth = {
          dayCellContent(item){
            let dev = _this.getHtml(item);
            let date = safeNewDate(item.date).toLocaleDateString().split('/');
            const { festival, lunarFestival, Term, IDayCn } = lunar.solar2lunar(date[0], date[1], date[2]);
            const f = festival || lunarFestival || Term || IDayCn;
            let paiban = val ? dev : '';
            if(currentYear == date[0] && currentMonth == date[1] && currentDay == date[2]) {
              if(shbLocale == 'zh') {
                return {html:`<span class="current-month-day" >${date[2]}</span><span style="padding: 4px;font-size: 12px;">${f}</span>${ paiban}`}
              }else {
                return {html:`<span class="current-month-day" >${date[2]}</span>${ paiban}`}
              }
            }
            if(shbLocale == 'zh') {
              return {html:`<span style="padding: 4px;color: #262626;">${date[2]}</span><span style="padding: 4px;font-size: 12px;color: #8c8c8c;">${f}</span>${ paiban}`}
            }else {
              return {html:`<span style="padding: 4px;color: #262626;">${date[2]}</span>${ paiban}`}
            }
          }
        }
      }else{
        _this.paiban = _this.ban.voList && _this.ban.voList[0] && _this.ban.voList[0].workSchedulingVoList[0]
          ? _this.ban.voList[0].workSchedulingVoList[0]
          : {};
      }
      this.getAgendaCalendar();
    },
    used() {
      this.openGuidanceDialog();
    },
    openGuidanceDialog() {
      this.$nextTick(() => {
        this.$refs.GuidanceDialog.visible = true;
        localStorage.setItem('calendermp4', '1');
      });
    },
    getCurrentWeekTime(now) {
      // 获取当前时间周的开始时间和结束时间
      let nowDayOfWeek = now.getDay(); // 今天本周的第几天
      let nowDay = now.getDate(); // 当前日
      let nowMonth = now.getMonth(); // 当前月
      let day = nowDayOfWeek + 1 || 7;
      this.currentWeekStart = formatDate(
        safeNewDate(now.getFullYear(), nowMonth, nowDay + 1 - day),
        'yyyy-MM-dd'
      );
      this.currentWeekend = formatDate(
        safeNewDate(now.getFullYear(), nowMonth, nowDay + 7 - day),
        'yyyy-MM-dd'
      );
    },
    async getTaskPlanFlag() {
      try {
        let calendarStatus = await getSettingCalendar();
        this.taskPlanningBtn = calendarStatus.data.status;
      } catch (error) {
        console.warn(error);
      }
    },
    async getEventPlanFlag() {
      try {
        let eventCalendar = await EventApi.calendarEventShow();
        this.eventPlanningBtn = eventCalendar.data;
      } catch (error) {
        console.warn(error);
      }
    },
    /** 日程管理需求-日程初始化设置提醒 */
    planningTime() {
      if (!this.planTimeTypeCheckbox)
        return this.$platform.alert(this.$t('calendar.checkOperation'));
      this.$confirm(this.$t('common.base.tip.planningTimeConfirmContent'), this.$t('common.base.tip.confirmTips'), {
        confirmButtonText: this.$t('common.base.makeSure'),
        cancelButtonText: this.$t('common.base.cancel'),
        type: 'warning',
      }).then(() => {
        postSettingPlanTime({ planTimeTypeCode: this.planTimeTypeCode })
          .then(async res => {
            console.log(res);
            if (res.code != 0) this.$platform.alert(res.message);

            await this.getTaskPlanFlag();
            this.planningTimeDialog = false;
            if (this.taskPlanningBtn == 2) {
              this.checkList.push(this.$t('common.base.task'));
            }

            this.$platform.notification({
              message: this.$t('calendar.openText'),
              type: 'success',
            });
          })
          .catch();
      });
    },
    /** 开通事件 */
    openEvent() {
      EventApi.openCalendarEvent({})
        .then(async res => {
          console.log(res);
          if (res.status != 0) this.$platform.alert(res.message);

          this.eventPlanningBtn = false;
          await this.getEventPlanFlag();
          this.eventPlanningTimeDialog = false;
          if (this.eventPlanningBtn) {
            this.checkList.push(this.$t('common.base.event'));
          }

          this.$platform.notification({
            message: this.$t('calendar.openSuccess'),
            type: 'success',
          });
        })
        .catch();
    },
    refresh(isResize) {
      return new Promise(resolve => {
        document.title = this.$t('common.pageTitle.pageSchedule');
        this.$refs.agendaDetailRef?.close();
        this.refreshView(isResize);
        resolve();
      });
    },
    getScrollHeight() {
      let box = document.getElementsByClassName(
        'fc-scroller fc-scroller-liquid-absolute'
      );
      const harness = document.querySelectorAll(
        '.fc-scrollgrid-section-header .fc-scroller-harness'
      );
      // debugger
      box[0].addEventListener('scroll', el => {
        this.scrollHeight = el.srcElement.scrollTop;
        harness.forEach(item => {
          if (
            item
            && this.scrollHeight > 20
            && (!this.calendarOptions.allDaySlot || this.isTeamDay)
          ) {
            item.style['box-shadow'] = '0px 12px 10px -5px rgba(0, 0, 0, 0.08)';
          } else {
            item.style['box-shadow'] = 'none';
          }
        });
      });
    },
    async getAgendaConfig() {
      try {
        const res = await CalendarApi.getAgendaConfig();
        if (res.status != 0) {
          return this.$platform.notification({
            title: res.message,
            type: 'error',
          });
        }
        this.planTimeConfig = res.data || 30;
      } catch (err) {
        console.error('err', err);
      }
    },
    getStartTimeAndEndTime() {
      const title = document
        .querySelector('.fc-toolbar-title')
        .innerText.replace(/\s*/g, '');
      const [ start, end ] = title.split('–');
      const startTime = getTimestamp(start)
      const endTime = getTimestamp(end || start, '23:59:59');
      return { startTime, endTime };
    },
    isInCalendar(event) {
      // 判断点击区域是否在日历内容区
      let div = document.querySelector('#calendar');
      let clientX = event.clientX;
      let clientY = event.clientY;
      let offsetLeft = div.offsetLeft;
      let offsetTop = div.offsetTop;
      let offsetWidth = div.offsetLeft + div.offsetWidth;
      let offsetHeight = div.offsetTop + div.offsetHeight;
      if (
        clientX < offsetLeft
        || clientX > offsetWidth
        || clientY < offsetTop
        || clientY > offsetHeight
      ) {
        this.closePopper();
      }
    },
    refreshView(isResize) {
      // 刷新视图
      this.getMiniCalendarAgendas();
      this.getAgendaCalendar(undefined, isResize);
    },
    // 新建工单日程
    async createTaskAgenda(params) {
      try {
        let res = await CalendarApi.createTaskAgenda(params);
        if (res.code != 0) {
          return this.$platform.notification({
            title: res.message,
            type: 'error',
          });
        }
        // 如果附加组件必填
        if (res.result && res.result.hasNotNullCard) {
          return this.$platform.notification({
            title: res.result.hasNotNullCard,
            type: 'error',
          });
        }
        // 如果需要审批
        if (res.result && res.result.needApprove) {
          let taskId = res.result.taskId;
          let executorId = params.allotForm.executorId;
          return this.$http
            .post('/task/confirmAllotTo', { taskId, executorId })
            .then(res => {
              this.$refs?.proposeApprove?.openDialog(res.data, () => {
                this.refreshView();
              });
            });
        }
        this.$platform.notification({
          title: this.$t('common.base.tip.createSuccess'),
          type: 'success',
        });
        // this.$refs.agendaDialogRef.reset();
        this.refreshView();
      } catch (err) {
        console.error('err', err);
      }
    },
    // 新建事件日程后刷新界面
    async createEventAgenda() {
      this.refreshView();
    },
    // 新建日程
    async submit(info) {
      let params = JSON.parse(JSON.stringify(info));
      params.users = params.users.map(item => item.userId);
      if (params.minutes == 0) {
        // 无提醒
        params.noticeType = 0;
        params.noticeContent = '';
      }

      // console.info('params', params);
      try {
        let res;
        if (params.id) {
          res = await CalendarApi.editAgenda(params, params.query);
        } else {
          // 从合同详情跳转过来的新建日程，只要新建都需要传递合同ID和类型;新建完成以后需要关闭tab，打开合同详情
          const { objectType, objectId } = query;
          if(objectType && objectId) {
            params.sourceType = parseInt(objectType);
            params.sourceId = objectId;
          }
          res = await CalendarApi.createAgenda(params, params.query);
        }
        if (res.status != 0) {
          this.$refs.agendaDialogRef.resetPending();
          return this.$platform.notification({
            title: res.message,
            type: 'error',
          });
        }
        this.$platform.notification({
          title: this.$t('common.base.tip.operationSuccess'),
          type: 'success',
        });
        const { objectType, objectId, contractId } = query;
        if(objectType && objectId) {
          // 新建日程后跳转到合同详情
          this.closeAndOpenTab(objectId)
          return;
        }else if(contractId) {
          // 编辑日程跳转到合同详情
          this.closeAndOpenTab(contractId)
          return;
        }
        this.$refs.agendaDialogRef.close();
        this.refreshView();
      } catch (err) {
        console.error('err', err);
      }
    },
    // 跳转
    closeAndOpenTab(id) {
      let ids = window.frameElement.dataset.id;
      this.$platform.closeTab(ids);
      let fromId = window.frameElement.getAttribute('id');
      openAccurateTab({
        type:PageRoutesTypeEnum.PageContractView,
        key:id,
        fromId
      });
    },
    // 获取mini视图当月的日程
    async getMiniCalendarAgendas() {
      this.markDate = [];
      if (!this.checkedDate) return;
      const arr = this.checkedDate.split('-');
      const params = {};
      params.year = arr[0];
      params.month = +arr[1];
      try {
        const res = await CalendarApi.getMiniCalendarAgendas(params);
        if (res.status != 0) {
          return this.$platform.notification({
            title: res.message,
            type: 'error',
          });
        }
        this.markDate = JSON.parse(
          JSON.stringify(res.data || []).replace(/-/g, '/')
        );
      } catch (err) {
        console.error('err', err);
      }
    },
    // 获取日历视图
    async getAgendaCalendar(selectDate, isResize) {
      if (this.isTeamDay && this.users.length <= 0) {
        this.calendarOptions.resources = [
          { id: this.$t('calendar.noSelectedUser'), title: this.$t('calendar.noSelectedUser') },
        ];
        this.calendarOptions.allDaySlot = false;
        this.calendarOptions.selectable = false;
        calendarApi.changeView(this.viewType);
        this.getScrollHeight();
        calendarApi.scrollTime = this.handleScrollTime();
        return;
      }

      this.calendarOptions.events = [];
      if (!this.checkList.length) return;
      let params = {};
      if (selectDate) {
        params.startTime = +dayTimeStart(selectDate);
        params.endTime = +dayTimeEnd(selectDate);
      } else {
        params = this.getStartTimeAndEndTime();
      }
      // const selectDate = formatDate(calendarApi.getDate(), 'yyyy-MM-dd')
      // const arr = selectDate.split('-')
      // params.startTime = `${arr[0]}-${arr[1]}-01`
      // const firstDay = safeNewDate(`${arr[0]}-${+arr[1] + 1}-01`)
      // let lastDay;
      // if(arr[1] == 12) {
      // // 如果是12月
      //   lastDay = 31
      // } else {
      //   lastDay = safeNewDate(firstDay.getTime() - (1000 * 60 * 60 * 24)).getDate()
      // }
      // params.endTime = `${arr[0]}-${arr[1]}-${lastDay}`

      params.type = this.calendarType;
      const countType = [];
      const typeTransferMap = [
        {
          text: t('common.base.task'),
          value: 2
        },
        {
          text: t('common.base.event'),
          value: 1
        },
        {
          text: t('calendar.commonAgenda'),
          value: 3
        }
      ]
      for (const key in this.checkList) {
        typeTransferMap.map(item=> {
          if(item.text == this.checkList[key] ) {
            countType.push(item.value)
          }
        })
      }
      params.countType = countType;
      params.users = this.users.map(item => item.userId);
      // console.info('params', params)
      try {
        this.loading = true;

        let action = this.isTeamDay
          ? 'getAgendaCalendarUser'
          : 'getAgendaCalendar';
        const res = await CalendarApi[action](params);
        if (res.status != 0) {
          return this.$platform.notification({
            title: res.message,
            type: 'error',
          });
        }

        const events = [];
        let allDaySlotFlag = false;
        if (this.isTeamDay) {
          let agendaResultDtoList = [];
          this.calendarOptions.resources = res.data
            && res.data.map((x, index) => {
              agendaResultDtoList = agendaResultDtoList.concat(
                x.agendaResultDtoList
              );
              return {
                id: x.userInfo.userId,
                index,
                title: x.userInfo.userName,
                headImage: x.userInfo.head,
                isTop: false,
              };
            });
          this.calendarOptions.resourceAreaColumns = [
            {
              cellContent: this.handlerResourseContent,
            },
          ];
          this.calendarData = agendaResultDtoList || [];
          agendaResultDtoList
            && agendaResultDtoList.forEach(item => {
              if (item.daySpan) allDaySlotFlag = true;
              events.push(this.genEvent(item));
            });
        } else {
          this.calendarData = res.data || [];
          res.data
            && res.data.forEach(item => {
              if (item.daySpan) allDaySlotFlag = true;
              events.push(this.genEvent(item));
            });
        }
        this.calendarOptions.allDaySlot = allDaySlotFlag;
        this.calendarOptions.events = events;

        if (this.isTeamDay) {
          this.calendarOptions.selectable = false;
          calendarApi.changeView(this.viewType);
          calendarApi.scrollTime = this.handleScrollTime();
          this.getScrollHeight();
        } else if (this.viewType == 'timeGridDay') {
          this.calendarOptions.selectable = this.canBaseCalendarAdd;
          calendarApi.changeView('timeGridDay');
          calendarApi.scrollTime = this.handleScrollTime();
        }
        if (isResize) {
          // 手动触发resize让FullCalendar插件更新
          setTimeout(() => {
            const myEvent = new Event('resize');
            window.dispatchEvent(myEvent);
            let id = window.frameElement.dataset.id;
            this.$platform.goOpenTab(id);
            this.loading = false;
          }, 500);
        } else {
          this.loading = false;
        }

        this.$nextTick(() => {
          this.setShadowStyle();
        });
      } catch (err) {
        this.loading = false;
        console.error('err', err);
      }
    },
    // 根据类型获取事件
    genEvent(event) {
      let {
        daySpan,
        daySpanStartTime,
        daySpanEndTime,
        startTime,
        endTime,
      } = event;
      // 在周视图中时间要显示整天的
      if (this.viewType === 'resourceTimelineWeek') {
        startTime = formatDate(dayTimeStart(event.startTime));
        endTime = formatDate(dayTimeEnd(event.endTime));
      }
      const tempObj = {
        id: event.agendaId,
        objId: event.objId,
        title: event.name,
        start: daySpan ? daySpanStartTime : startTime,
        end: daySpan ? daySpanEndTime : endTime,
        type: event.type,
        head: event.head,
        allDay: daySpan,
        currentId: event.id,
      };
      if (this.isTeamDay) {
        tempObj.resourceId = event.userId;
      }
      if (this.viewType === 'resourceTimelineDay') {
        tempObj.start = startTime;
        tempObj.end = endTime;
        tempObj.allDay = false;
      }
      const typeObj = { 1: 'event', 2: 'task', 3: 'common' };
      // 取消和拒绝状态
      let cancelStyle = event.cancel == 1 || event.status == 2 ? 'event-cancle' : '';
      let isAllDayStyle = event.daySpan && (event.cancel == 1 || event.status == 2)
        ? 'event-cls-through'
        : '';
      tempObj.classNames = [
        'event-cls',
        `event-cls-${typeObj[event.type]}`,
        cancelStyle,
        isAllDayStyle,
      ];
      return tempObj;
    },
    createAgenda(type) {
      const typeObj = { event: 1, task: 2, common: 3 };
      this.agendaType = typeObj[type];
      const startTime = getPlanStartTime();
      const endTime = getPlanEndTime(this.planTimeConfig, startTime);
      this.$nextTick(() => {
        if (type == 'task') {
          // 跳转新建工单 带上计划开始和结束时间
          if (!this.taskTypeList.length)
            return this.$platform.alert(
              this.$t('calendar.taskErrorText')
            );
          this.taskStartTime = startTime;
          this.taskEndTime = endTime;
          this.$refs.agendaTaskDialogRef.show();
        } else if (type == 'event') {
          // 跳转新建事件
          if (!this.eventTypeList.length)
            return this.$platform.alert(
              this.$t('calendar.eventErrorText')
            );
          this.eventStartTime = startTime;
          this.eventEndTime = endTime;
          this.$refs.agendaEventDialogRef.show();
        } else {
          this.agendaInfo = {};

          const day = formatDate(calendarApi.getDate(), 'yyyy-MM-dd');
          const hours = formatDate(safeNewDate(), 'HH:mm:ss');

          this.startTime = getPlanStartTime(
            safeNewDate(`${day} ${hours}`)
          );
          this.endTime = getPlanEndTime(
            this.calendarOptions.planTimeConfig,
            this.startTime
          );
          this.$refs.agendaDialogRef.show();
        }
      });
    },
    // 舍弃不使用
    openTab(url, type) {
      let fromId = window.frameElement.getAttribute('id');
      this.$platform.openTab({
        id: `create${type}`,
        title: this.$t('common.base.isLoading2'),
        url,
        close: true,
        fromId,
      });
    },
    dateChange(date) {
      // 日期改变触发
      // console.info(date, 'change')
      this.checkedDate = date;
      this.$nextTick(() => {
        this.currentDateStr = this.dateFormat(safeNewDate(date));
        // this.getCurrentWeekTime(safeNewDate(date));
        if (this.dateChangeFlag) {
          this.dateChangeFlag = false;
          this.dateClick(date);
        }
      });
      if (this.$refs.picker.getIsNeedUpdate()) {
        this.getMiniCalendarAgendas();
      }
    },
    dateClick(date) {
      // 点击日期时按钮触发
      this.checkedDate = date;
      // 切换成某天的日视图
      if (this.calendarType === 2) {
        this.viewType = 'resourceTimelineDay';
        calendarApi.changeView('resourceTimelineDay');
      } else {
        this.viewType = 'timeGridDay';
        calendarApi.changeView('timeGridDay');
      }
      calendarApi.gotoDate(date);
      this.currentDateStr = this.dateFormat(calendarApi.getDate());
      // this.getCurrentWeekTime(calendarApi.getDate());
      this.isToday = this.getIsToday();
      // if(this.$refs.picker.getIsNeedUpdate()) {
      this.getAgendaCalendar(
        formatDate(calendarApi.getDate(), 'yyyy-MM-dd')
      );
      // }
    },
    toggleMiniWeekMonth() {
      if (this.isMiniMonthView) {
        this.$refs?.picker?.showWeek();
        this.isMiniMonthView = false;
      } else {
        this.$refs?.picker?.showMonth();
        this.isMiniMonthView = true;
      }
    },
    pre() {
      // if(this.isMiniMonthView()) {
      //   // 月视图 上月
      //   this.viewType = 'dayGridMonth'
      //   calendarApi.changeView('dayGridMonth')
      // }else {
      //   // 周视图 上周
      //   this.viewType = 'timeGridWeek'
      //   calendarApi.changeView('timeGridWeek')
      // }
      // calendarApi.prev()
      // this.currentDateStr = this.dateFormat(calendarApi.getDate())
      this.dateChangeFlag = true;
      this.$refs.picker.getPre();
    },
    next() {
      // if(this.isMiniMonthView()) {
      //   // 月视图 上月
      //   this.viewType = 'dayGridMonth'
      //   calendarApi.changeView('dayGridMonth')
      // }else {
      //   // 周视图 上周
      //   this.viewType = 'timeGridWeek'
      //   calendarApi.changeView('timeGridWeek')
      // }
      // calendarApi.next()
      // this.currentDateStr = this.dateFormat(calendarApi.getDate())
      this.dateChangeFlag = true;
      this.$refs.picker.getNext();
    },
    getIsToday() {
      return (
        formatDate(calendarApi.getDate(), 'yyyy-MM-dd') == formatDate(safeNewDate(), 'yyyy-MM-dd')
      );
    },
    // 切换到上一页
    prevFn() {
      calendarApi.prev();
      const date = calendarApi.getDate();
      this.currentDateStr = this.dateFormat(date);
      // this.getCurrentWeekTime(date);
      // this.getAgendaCalendar();
      this.isToday = this.getIsToday();
      let type = calendarApi.view.type;
      if (type == 'timeGridDay' || type == 'resourceTimelineDay') {
        this.$refs.picker.clickCalendarDay({
          year: date.getFullYear(),
          month: date.getMonth(),
          day: date.getDate(),
        });
      }
      // if(type == 'timeGridWeek' && this.isMiniMonthView()) {
      //   this.$refs.picker.showWeek()
      // }else if(type == 'dayGridMonth' && !this.isMiniMonthView()){
      //   this.$refs.picker.showMonth()
      // }
      // this.$refs.picker.getPre()
      this.rili(this.paibanList);
    },
    // 切换到下一页
    nextFn() {
      calendarApi.next();
      const date = calendarApi.getDate();
      this.currentDateStr = this.dateFormat(date);
      // this.getCurrentWeekTime(date);
      // this.getAgendaCalendar();
      this.isToday = this.getIsToday();
      let type = calendarApi.view.type;
      if (type == 'timeGridDay' || type == 'resourceTimelineDay') {
        this.$refs.picker.clickCalendarDay({
          year: date.getFullYear(),
          month: date.getMonth(),
          day: date.getDate(),
        });
      }
      // if(type == 'timeGridWeek' && this.isMiniMonthView()) {
      //   this.$refs.picker.showWeek()
      // }else if(type == 'dayGridMonth' && !this.isMiniMonthView()){
      //   this.$refs.picker.showMonth()
      // }
      // this.$refs.picker.getNext()
      this.rili(this.paibanList);
    },
    // 切换到今天
    todayFn() {
      /* if (this.calendarType === 2) {
        this.viewType = 'resourceTimelineDay'
        calendarApi.changeView('resourceTimelineDay')
      } else {
        this.viewType = 'timeGridDay'
        calendarApi.changeView('timeGridDay')
      }*/
      calendarApi.today()
      this.currentDateStr = this.dateFormat(calendarApi.getDate(), 'YYYY-mm-dd WWW')
      // this.getCurrentWeekTime(calendarApi.getDate());
      this.isToday = this.getIsToday();
      // mini日历
      this.$refs.picker.today();
      // this.getAgendaCalendar();
      this.rili(this.paibanList);
    },
    // 切换显示类型
    changeViewTypeFn(type, mode) {
      // 如果是手动点击触发
      if(mode === 'handle') {
        this.$track.clickStat(this.$track.formatParams('CALENDAR_SWITCH_VIEW_TYPE', this.viewTypeMap[type]));
      }

      calendarApi.changeView(type);
      this.currentDateStr = this.dateFormat(calendarApi.getDate());
      // this.getCurrentWeekTime(calendarApi.getDate());
      this.isToday = this.getIsToday();
      this.getScrollHeight();
      // this.getAgendaCalendar();
      this.rili();
    },
    dateFormat(date, format = 'YYYY-mm-dd WWW') {
      // 日视图显示 年月日 周几
      let type = calendarApi ? calendarApi.view.type : 'timeGridDay'
      if (type != 'timeGridDay' && type !== 'resourceTimelineDay') {
        format = 'YYYY-mm'
      }
      let we = date.getDay(); // 星期
      const opt = {
        'Y+': date.getFullYear().toString(), // 年
        'm+': (date.getMonth() + 1).toString(), // 月(月份从0开始，要+1)
        'd+': date.getDate().toString(), // 日
      };
      const week = {
        // 中文数字 (星期)
        0: this.$t('common.base.aboutTime.sunday'),
        1: this.$t('common.base.aboutTime.monday'),
        2: this.$t('common.base.aboutTime.tuesday'),
        3: this.$t('common.base.aboutTime.wednesday'),
        4: this.$t('common.base.aboutTime.thursday'),
        5: this.$t('common.base.aboutTime.friday'),
        6: this.$t('common.base.aboutTime.saturday'),
      };
      const week2 = {
        // 中文数字 (星期)
        0: this.$t('common.base.aboutTime.Sun'),
        1: this.$t('common.base.aboutTime.Mon'),
        2: this.$t('common.base.aboutTime.Tue'),
        3: this.$t('common.base.aboutTime.Wed'),
        4: this.$t('common.base.aboutTime.Thu'),
        5: this.$t('common.base.aboutTime.Fri'),
        6: this.$t('common.base.aboutTime.Sat'),
      };
      if (/(W+)/.test(format)) {
        format = format.replace(
          RegExp.$1,
          RegExp.$1.length > 1
            ? RegExp.$1.length > 2
              ? week[we]
              : week2[we]
            : week[we]
        );
      }
      for (let k in opt) {
        let r = new RegExp(`(${k})`).exec(format);
        if (r) {
          // 若输入的长度不为1，则前面补零
          format = format.replace(
            r[1],
            RegExp.$1.length == 1
              ? opt[k]
              : opt[k].padStart(RegExp.$1.length, '0')
          );
        }
      }
      return format;
    },
    // 事件被渲染
    eventDidMount(info) {
      // if(!this.isTeamDay){
      // 日视图和周视图 团队日历显示头像
      // console.info('eventDidMount', info.event)
      /* setTimeout(() => {
        // 个人日历和团队日历新建都不显示头像
          if(this.calendarType == 2 && this.viewType != 'dayGridMonth' && !popper) {
            const head = info.event.extendedProps.head || defaultAvatar
            info.el.innerHTML = `<div class="fc-event-main"><div class="fc-event-main-frame"><div class="fc-event-title-container">
          <div class="fc-event-title fc-sticky"><img src=${head}>${info.event.title}</div></div></div></div>`
          }
        }, 800);*/
      this.$nextTick(() => {
        if (this.viewType === 'dayGridMonth') {
          let parentDom = info.el;
          if (parentDom.classList.contains('fc-daygrid-block-event')) {
            let dom = parentDom.getElementsByClassName(
              'fc-event-main-frame'
            )[0];
            let childDom = document.createElement('div');
            childDom.innerHTML = '<div class="fc-daygrid-event-dot"></div><div class="fc-event-time"></div>';
            // 跨天日程加上时间
            if (info.event.allDay) {
              let startTime = '';
              let id = info.event.id;
              const item = this.calendarData.filter(x => {
                if (x.agendaId == id) {
                  // 因为跨天日程也可以循环
                  // 如果一天里面有两个跨天(跨天循环的情况)的需要在判断开始时间是否一样才能渲染，不能通过agendaId去唯一判断
                  let segStart = formatDate(
                    safeNewDate(x.startTime),
                    'yyyy-MM-dd'
                  );
                  let eventStart = formatDate(
                    safeNewDate(info.event.startStr),
                    'yyyy-MM-dd'
                  );
                  if (segStart == eventStart) {
                    return x;
                  }
                }
              });
              if (item && item.length) {
                if (item[0].startTime)
                  startTime = formatDate(
                    safeNewDate(item[0].startTime),
                    'HH:mm'
                  );
                childDom.innerHTML = `<div class="fc-daygrid-event-dot"></div><div class="fc-event-time">${startTime}</div>`;
              }
            }
            childDom.classList.add('fc-dot-pa');
            dom.insertBefore(childDom, dom.childNodes[0]);
          }
        } else {
          // 只给团队日历的周视图加时间
          let parentDom = info.el;
          if (parentDom.classList.contains('fc-timeline-event')) {
            let dom = parentDom.getElementsByClassName('fc-event-title')[0];
            // 日程加上时间
            let startTime = formatDate(
              safeNewDate(info.event.startStr),
              'HH:mm'
            );
            let id = info.event.id;
            if (this.viewType === 'resourceTimelineWeek') {
              const item = this.calendarData.filter(x => {
                if (x.agendaId == id) {
                  // 因为跨天日程也可以循环
                  // 如果一天里面有两个跨天(跨天循环的情况)的需要在判断开始时间是否一样才能渲染，不能通过agendaId去唯一判断
                  let segStart = formatDate(
                    safeNewDate(x.startTime),
                    'yyyy-MM-dd'
                  );
                  let eventStart = formatDate(
                    safeNewDate(info.event.startStr),
                    'yyyy-MM-dd'
                  );
                  if (segStart == eventStart) {
                    return x;
                  }
                }
              });
              if (item && item.length) {
                if (item[0].startTime)
                  startTime = formatDate(
                    safeNewDate(item[0].startTime),
                    'HH:mm'
                  );
              }
              if (info.event.allDay) {
                dom.innerText = `${this.$t('calendar.crossDay')}: ${startTime}  ${dom.innerText}`;
              } else {
                dom.innerText = `${startTime}  ${dom.innerText}`;
              }
            } else if (this.viewType === 'resourceTimelineDay') {
              // 手动计算是否跨天
              let start = formatDate(
                safeNewDate(info.event.startStr),
                'yyyy-MM-dd'
              );
              let end = formatDate(
                safeNewDate(info.event.endStr),
                'yyyy-MM-dd'
              );
              if (start < end) {
                dom.innerText = `${this.$t('calendar.crossDay')}: ${dom.innerText}`
              }
            }
          }
        }
      });
      // }
    },
    eventWillUnmount(info) {
      // console.info('eventWillUnmount', info.event)
    },
    // 点击某一天
    handleDateClick(arg) {
      // console.info(`date click! ${arg.dateStr}`, arg)
    },
    handleDateSelect(selectInfo) {
      selectStartTime = formatDate(selectInfo.start);
      selectEndTime = formatDate(selectInfo.end);
      this.closePopper();

      if (!this.isTeamDay) {
        // 暂时去除事件&工单
        this.agendaHandler({ target: { innerHTML: this.$t('calendar.commonAgenda') } });
      }

      // this.createPopper()
    },
    genTemplate() {
      return `
      <div class="base-tooltip base-tooltip-agenda" v-clickoutside="closePopper">
        <div class="base-tooltip-content task-agenda">工单日程</div>
        <div class="base-tooltip-content event-agenda">事件日程</div>
        <div class="base-tooltip-content common-agenda">通用日程</div>
      </div>
    `;
    },
    closePopper() {
      popper && popper.destroy();
      popper = null;
      el = null;
    },
    createPopper() {
      if (null == el) {
        let container = dom.fromHtml(this.genTemplate());
        container.addEventListener('click', this.agendaHandler);
        el = document.body.appendChild(container);
        document.querySelector('.task-agenda').style.display = this
          .allowCreateTask
          ? 'block'
          : 'none';
        document.querySelector('.event-agenda').style.display = this
          .allowCreateEvent
          ? 'block'
          : 'none';
        document.querySelector('.common-agenda').style.display = this
          .allowCreateAgenda
          ? 'block'
          : 'none';
      }
      if (null == popper) {
        popper = new Popper(document.querySelector('.fc-highlight'), el, {
          removeOnDestroy: true,
        });
      }
    },
    agendaHandler(e) {
      // console.info('e', e);
      const text = e.target.innerHTML;
      const startTime = selectStartTime;
      // 计划完成时间不从设置里面获取然后计算了
      const endTime = selectEndTime;
      // this.endTime = getPlanEndTime(this.planTimeConfig, selectStartTime)
      // console.log(this.startTime, this.endTime);
      if (text == '通用日程') {
        this.startTime = startTime;
        this.endTime = endTime;
        this.$nextTick(() => {
          this.$refs.agendaDialogRef.show();
        });
      } else if (text == '工单日程') {
        // 判断工单类型是否为空
        if (!this.taskTypeList.length)
          return this.$platform.alert(
            this.$t('calendar.taskErrorText')
          );
        this.taskStartTime = startTime;
        this.taskEndTime = endTime;
        this.$nextTick(() => {
          this.$refs.agendaTaskDialogRef.show();
        });
      } else if (text == '事件日程') {
        // 判断事件类型是否为空
        if (!this.eventTypeList.length)
          return this.$platform.alert(
            this.$t('calendar.eventErrorText')
          );
        this.eventStartTime = startTime;
        this.eventEndTime = endTime;
        this.$nextTick(() => {
          this.$refs.agendaEventDialogRef.show();
        });
      }
      this.closePopper();
    },
    handleEventClick(clickInfo) {
      // console.info('clickInfo', clickInfo);
      const el = document.querySelector('.fc-more-popover');
      if (el) el.style.display = 'none';
      const { extendedProps, start, end } = clickInfo.event;
      const { type } = extendedProps;
      let startTime = start;
      let endTime = end;
      // this.agendaType = type
      this.$nextTick(() => {
        if (type == 1) {
          this.eventId = extendedProps.objId;
          this.$refs.agendaEventDetailRef.showDetail(this.eventId);
        } else if (type == 2) {
          this.taskId = extendedProps.objId;
          this.$refs.agendaTaskDetailRef.showDetail(this.taskId);
        } else {
          this.agendaId = clickInfo.event.id;
          if (
            clickInfo.event.allDay
            || this.viewType === 'resourceTimelineWeek'
          ) {
            const item = this.calendarData.filter(x => {
              if (x.agendaId == this.agendaId) {
                // 因为跨天日程也可以循环
                // 如果一天里面有两个跨天(跨天循环的情况)的需要在判断开始时间是否一样才能渲染，不能通过agendaId去唯一判断
                let segStart = formatDate(
                  safeNewDate(x.startTime),
                  'yyyy-MM-dd'
                );
                let eventStart = formatDate(
                  safeNewDate(clickInfo.event.start),
                  'yyyy-MM-dd'
                );
                if (segStart == eventStart) {
                  return x;
                }
              }
            });
            if (item && item.length) {
              if (item[0].startTime)
                startTime = formatDate(safeNewDate(item[0].startTime));
              if (item[0].endTime)
                endTime = formatDate(safeNewDate(item[0].endTime));
            }
          }
          let timeInfo = {
            start: startTime,
            end: endTime,
            agendaId: this.agendaId,
          };

          this.$refs.agendaDetailRef.showDetail(timeInfo);
        }
      });
      this.closePopper();
    },
    handleMoreLinkDidMount(info) {
      info.el.innerHTML = `<div>${info.shortText}</div>`;
    },
    handleMoreLinkContent(info) {
      info.text = '';
    },
    handleMoreLinkClick() {
      this.closePopper();
    },
    handleEventMouse(info) {
      tippy(info.el, {
        content: info.el.innerText,
        // placement: 'left',
      });
    },
    handleScrollTime() {
      let currentDate = safeNewDate();
      if (currentDate.getHours() < 2) {
        return '00:00:00';
      }
      // 若当前时间过去了两个小时，则跳转到的时间减去两个小时
      return formatDate(safeNewDate() - 2 * 60 * 60 * 1000, 'HH:mm:ss');
    },
    /* 处理人员头像*/
    handlerResourseContent(arg) {
      if (this.calendarType === 2) {
        if (arg.resource.id !== '暂未选择人员') {
          let extendedProps = arg.resource.extendedProps;
          const head = (extendedProps && extendedProps.headImage) || defaultAvatar;
          const userId = (arg.resource && arg.resource.id) || '';
          let isTop = extendedProps && extendedProps.isTop; // 是否已经置顶
          let index = extendedProps && extendedProps.index; // 是否是第一个元素
          let tooltip1 = '<div role="tooltip" id="el-tooltip-7910" aria-hidden="false" class="el-tooltip__popper is-dark none" x-placement="top-start">置顶<div x-arrow="" class="popper__arrow" ></div></div>';
          let tooltip2 = '<div role="tooltip" id="el-tooltip-7910" aria-hidden="false" class="el-tooltip__popper is-dark none"  x-placement="top-start">删除<div x-arrow="" class="popper__arrow"></div></div>';
          let peopleHtml = `<div class="team-people-resourse">
            <div class="team-people-name" style="cursor:pointer;" user-id=${userId} onclick="openCalendarUserCard(this)">
              <img src=${head} class="team-people-head">
              <span>${arg.fieldValue}</span>
            </div>
            <div class="team-people-icon">`;
          if (isTop) {
            // 不显示置顶图标，显示置顶标签
            peopleHtml = `${peopleHtml}<div class="shanchu fanzhuan">${tooltip2}<i class="iconfont icon-close" onclick="removeChoosePeople('${
              arg.resource.id
            }')"></i></div></div><div class="team-top-inner-triangle"></div></div>`;
          } else if (index === 0) {
            // 不显示置顶图标，不显示置顶标签
            peopleHtml = `${peopleHtml}<div class="shanchu fanzhuan">${tooltip2}<i class="iconfont icon-close" onclick="removeChoosePeople('${
              arg.resource.id
            }')"></i></div></div></div>`;
          } else {
            // 显示置顶图标，不显示置顶标签
            peopleHtml = `${peopleHtml}<div style="display: flex;"><div class="zhiding">${tooltip1}<i class="iconfont icon-vertical-align-top" onclick="moveTop('${
              arg.resource.id
            }')"></i></div><div class="shanchu">${tooltip2}<i class="iconfont icon-close" onclick="removeChoosePeople('${
              arg.resource.id
            }')"></i></div></div></div></div></div>`;
          }
          return { html: peopleHtml };
        }
      }
    },
    // 移除先择的团队人员
    removeChoosePeople(arg) {
      this.idSortSourses = true;
      // 获取删除元素的index,删除元素的后面元素的index都要减去1
      let currentIndex = -1;
      this.calendarOptions.resources.forEach(item => {
        if (item.id === arg) {
          currentIndex = item.index;
        }
      });
      this.users = this.users.filter(item => item.userId != arg);
      this.calendarOptions.resources = this.calendarOptions.resources.filter(
        item => item.id !== arg
      );
      this.calendarOptions.resources = this.calendarOptions.resources.map(
        item => {
          if (currentIndex < item.index) {
            // 移动到顶部以后，把这个元素之前的元素都要向下移动一个位置
            item.index -= 1;
          }
          return item;
        }
      );
      // 若当前没有用户应添加‘暂未选择人员’
      if (this.isTeamDay && this.users.length <= 0) {
        this.calendarOptions.resources = [
          { id: this.$t('calendar.noSelectedUser'), title: this.$t('calendar.noSelectedUser') },
        ];
        this.calendarOptions.allDaySlot = false;
        this.calendarOptions.selectable = false;
        this.getScrollHeight();
        calendarApi.scrollTime = this.handleScrollTime();
      }
    },
    // 置顶功能
    moveTop(arg) {
      // 获取置顶的元素对象
      let currentPeople = this.calendarOptions.resources.filter(
        item => item.id === arg
      ); // 获取置顶的元素对象
      let currentIndex = currentPeople[0].index; // resources的位置
      this.calendarOptions.resources = this.calendarOptions.resources.map(
        item => {
          item.isTop = false;
          if (arg === item.id) {
            item.index = 0;
            item.isTop = true;
          } else if (currentIndex > item.index) {
            // 移动到顶部以后，把这个元素之前的元素都要向下移动一个位置
            item.index += 1;
          }
          return item;
        }
      );
      this.sortUser();
    },
    /* cancleTop(arg) {
      let currentPeople = this.calendarOptions.resources.filter(item => item.id === arg ) // 获取置顶的元素对象
      let currentIndex = this.calendarOptions.resources.indexOf(currentPeople[0]) // 原来resources的位置
      this.calendarOptions.resources = this.calendarOptions.resources.map((item, index) => {
        if(currentIndex === index) { // 取消指定的元素，它的index修改为之前的值
          item.index = index;
          item.isTop = false; // 取消置顶
        }else if(currentIndex > index) { // 取消指定的元素之前位置之前的的元素都需要向上移动一位
          item.index -= 1;
        }else if(currentIndex < index) { // 取消指定的元素之前位置之后的的元素都需要向下移动一位
          item.index += 1;
        }
        return item;
      })
      this.sortUser();
    },*/
    sortUser() {
      // 左边选择人员排序
      this.users = this.users.map(item => {
        let people = this.calendarOptions.resources.filter(
          re => re.id === item.userId
        );
        if (people && people.length !== 0) {
          item.index = people[0].index;
        }
        return item;
      });
      this.idSortSourses = true;
      this.users.sort((a, b) => {
        return a.index - b.index;
      });
    },
    edit(id) {
      this.$refs.agendaDialogRef.show(id);
    },
    async del(params) {
      let info = null;
      if (params.api === 'deleteAgenda') {
        if (
          !(await this.$platform.confirm(this.$t('calendar.noRecoverConfirm')))
        )
          return;
        info = {
          agendaId: params.agendaId,
          deleteTime: formatDate(
            safeNewDate(params.deleteTime),
            'yyyy-MM-dd HH:mm:ss'
          ),
        };
      } else {
        if (
          !(await this.$platform.confirm(
            this.$t('calendar.delConfirm')
          ))
        )
          return;
        info = { agendaId: params.agendaId };
      }
      try {
        const res = await CalendarApi[params.api || 'deleteAgenda'](info);
        if (res.status != 0) {
          return this.$platform.notification({
            title: res.message,
            type: 'error',
          });
        }
        this.$platform.notification({
          title: this.$t('common.base.deleteSuccess'),
          type: 'success',
        });
        this.$refs.agendaDetailRef.close();
        // 页面刷新
        this.refreshView();
      } catch (e) {
        console.error('e', e);
      }
    },
    async cancel(agendaId) {
      try {
        if (!(await this.$platform.confirm(this.$t('calendar.cancelConfirm')))) return;
        const res = await CalendarApi.cancelAgenda({ agendaId });
        if (res.status != 0) {
          return this.$platform.notification({
            title: res.message,
            type: 'error',
          });
        }
        this.$platform.notification({
          title: this.$t('common.base.tip.cancelSuccess'),
          type: 'success',
        });
        this.$refs.agendaDetailRef.close();
        // 页面刷新
        this.refreshView();
      } catch (e) {
        console.error('e', e);
      }
    },
    // 删除工单
    async deleteTask(taskId, taskState) {
      try {
        let warningMsg = this.$t('common.base.tip.areYouSureYouWantDeletIt2');

        /**
         * 如果工单为未完成状态，则需要判断工单是否曾回退，而且在最后一次完成时是否使用了备件
         * 如果使用了备件，需要提示
         */
        let unfinishedStateArr = [
          'created',
          'allocated',
          'taskPool',
          'accepted',
          'refused',
          'processing',
        ];
        if (unfinishedStateArr.indexOf(taskState) >= 0) {
          const res = await TaskApi.finishedWithPart({ taskId });
          if (!res.success) {
            warningMsg = this.$t('calendar.unableJudgeText');
          } else if (res.success && res.result) {
            warningMsg = this.$t('calendar.delText');
          }
        }

        const result = await this.$platform.confirm(warningMsg);
        if (!result) return;

        TaskApi.deleteTask([taskId])
          .then(res => {
            if (res.success) {
              this.$platform.notification({
                title: this.$t('common.base.deleteSuccess'),
                type: 'success',
              });
              let fromId = window.frameElement.getAttribute('fromid');
              this.$platform.refreshTab(fromId);
              this.refreshView();
            } else {
              this.$platform.alert(res.message);
            }
          })
          .catch(err => {
            console.error('error', err);
          });
      } catch (e) {
        console.error('deleteTask error', e);
      }
    },
    // 删除事件
    async deleteEvent(id) {
      const result = await this.$platform.confirm(this.$t('common.base.tip.areYouSureYouWantDeletIt2'));
      if (!result) return;
      EventApi.eventDelete([id]).then(res => {
        if (res.status === 1) {
          this.$platform.alert(res.message);
        } else {
          this.$platform.notification({
            title: this.$t('common.base.deleteSuccess'),
            type: 'success',
          });
          let fromId = window.frameElement.getAttribute('fromid');
          this.$platform.refreshTab(fromId);
          this.refreshView();
        }
      });
    },
    handleEvents(events) {
      this.currentEvents = events;
    },
    head(user) {
      if (!user) return defaultAvatar;
      return user.head ? user.head : defaultAvatar;
    },
    delUser(index) {
      this.users.splice(index, 1);
    },
    setShadowStyle() {
      let shaded = document.querySelector('.fc-cell-shaded');
      if(!shaded) return;
      if(shaded.querySelector('.title-cell-shaded-shadow')) return; // 如果已经有阴影，不需要再加

      let dom = document.createElement('div');
      dom.className = 'title-cell-shaded-shadow';

      shaded.appendChild(dom);
      shaded.style.padding = 0;
      shaded.style.height = 0;
      shaded.style.border = 0;
    },
    async selectUser() {
      let selected = this.users;

      let flag = isAllotByDepartment();

      // let options = {
      //   title: '选择团队人员', // [选填] 默认值为 '请选择人员'
      //   max: 50, // [选填]最大人数：当值小于等于0或者不填时，不对选择人数做限制，max值为1时单选，大于1时多选
      //   selectedUsers: selected, // [选填] 已选人员 每个人员必须包括userId,displayName,staffId,head这四个属性，只有带max大于1时生效
      //   haveRole: true,
      //   isCalendar: true,
      //   calendarAction: `/calendar/query/user/tree?allotByTag=${!flag}`,
      //   calendarSeeAllOrg: !flag,
      // };
      let options = {
        title: this.$t('calendar.selectTeamUser'), // [选填] 默认值为 '请选择人员'
        max: 150, // [选填]最大人数：当值小于等于0或者不填时，不对选择人数做限制，max值为1时单选，大于1时多选
        selected, // [选填] 已选人员 每个人员必须包括userId,displayName,staffId,head这四个属性，只有带max大于1时生效
        unique: false,
        mode: BaseSelectUserModeEnum.Filter,
        // haveRole: true,
        // isCalendar: true,
        // calendarAction: `/calendar/add/user/tree?allotByTag=${!flag}`,
        // calendarSeeAllOrg: !flag,
        fetchDepartmentList: (params) => {
          
          const newParams = {
            ...params,
            allotByTag: !flag
          }
          
          return getSelectDepartmentCalendarUserList(newParams)
        }
      }
      /* FIXME: 选人组件 */
      this.$fast.select.multi.user(options).then(res => {
          if (res.status != 0) return;
          if (res.data.users && res.data.users.length > 150)
            return alert(this.$t('common.base.tip.maxChoosePerson', {data1: '150'}));
          this.users = res.data.users || [];
          this.users = this.users.map((item, index) => {
            return { ...item, index };
          });
        })
        .catch(err => {
          console.warn(err);
        });
    },
    /* 查询是否开启 降低组织架构的开关 */
    getSeeAllOrg() {
      return this.$http.post('/setting/user/getSeeAllOrg').then(result => {
        return result;
      });
    },

    // 人员卡片
    openCalendarUserCard(el){
      if(el.attributes['user-id']){
        this.$OpenUserCard({el, user:{userId:el.attributes['user-id']?.value}})
      }
    }
  },
  created() {
    let _this = this;
    window.removeChoosePeople = _this.removeChoosePeople;
    window.moveTop = _this.moveTop;
    window.cancleTop = _this.cancleTop;
    window.openCalendarUserCard = _this.openCalendarUserCard
  },
  destroyed() {
    document.removeEventListener('click', this.isInCalendar);
  },
};
</script>
<style lang="scss">
.banci {
  float: right;
  display: inline-block;
  width: 20px;
  height: 20px;
  border-radius: 2px;
  color: #fff;
  font-size: 12px;
  text-align: center;
  line-height: 20px;
}
.xiu {
  color: #52c41a;
  font-size: 12px;
	}
  .ban{
    color: red;
    font-size: 12px;
  }
</style>
<style lang="scss" scoped>
.calendar-view {
  display: flex;
  height: 100%;
  width: 100%;
  padding: 12px;

  .left-calendar {
    background: #fff;
    padding: 0 10px;
    margin-right: 10px;
    border-radius: 4px;
    max-width: 240px;
    overflow-y: auto;
    .zuoce {
      padding-bottom: 25px;
      min-height: 100%;
      position: relative;
      .shiyong {
        position: absolute;
        bottom: 14px;
        cursor: pointer;
        color: rgb(87, 107, 149);
        &:hover {
          text-decoration: underline;
        }
      }
    }
    .mini-calendar-create {
      background: #fff;
      padding: 12px 0px;
      button {
        width: 210px;
        font-size: 15px;
        border-radius: 4px !important;
      }
    }
    .mini-calendar-header {
      display: flex;
      padding: 12px 10px;
      background: #fff;
      align-items: center;
      .title {
        flex: 1;
      }
    }
    h4 {
      margin: 12px 0;
    }
    .stat-type {
      display: flex;
      flex-direction: column;
      .el-checkbox {
        margin-bottom: 12px;
      }
      .iconfont {
        font-size: 12px;
        display: inline-block;
        margin-left: 3px;
        color: #8c8c8c;
      }
    }
    .calendar-type {
      label {
        display: block;
        margin-bottom: 12px;
      }
    }
    .chosen-people {
      border: 1px solid #ddd;
      border-radius: 5px;
      padding: 4px;
      margin-top: 10px;
      .chosen-synergy-wrap {
        display: flex;
        flex-flow: row wrap;
        padding-bottom: 5px;
        .chosen-people-item {
          text-align: center;
          margin-bottom: 5px;
          margin-right: 10px;
          .chosen-people-btn {
            font-size: 26px;
            border: 1px dashed;
            border-radius: 50%;
            color: #666;
            margin-top: 5px;
            margin-left: 5px;
            padding: 4px;
          }
          .chosen-people-avatar {
            position: relative;
            width: 42px;
            height: 42px;
            margin-bottom: 5px;
            img {
              display: block;
              width: 100%;
              height: 100%;
              border-radius: 50%;
              border: 1px solid #e5e7e6;
              object-fit: cover;
            }
            .del-people {
              position: absolute;
              top: 0px;
              right: 0px;
              color: #999;
            }
          }
        }
      }
    }

    .checkbox-event {
      ::v-deep .el-checkbox__input.is-checked .el-checkbox__inner {
        border-color: #faae14 !important;
        background-color: #faae14 !important;
      }
    }
    .checkbox-common {
      ::v-deep .el-checkbox__input.is-checked .el-checkbox__inner {
        border-color: rgb(76, 175, 80) !important;
        background-color: rgb(76, 175, 80) !important;
      }
    }
    ::v-deep .el-checkbox__input.is-checked + .el-checkbox__label {
      color: #606266 !important;
    }
  }

  .right-calendar {
    width: 100%;
    flex: 1;
    background: #fff;
    padding-left: 10px;
    overflow: hidden;
    border-radius: 4px;
    .top-content {
      display: flex;
      align-items: center;
      position: sticky;
      top: 0;
      padding: 10px 0;
      &.showShadow {
        box-shadow: 0px 12px 10px -5px rgba(0, 0, 0, 0.05);
        z-index: 9;
        background-color: white;
      }
      .left {
        display: flex;
        align-items: center;
        margin-right: 30px;
        line-height: 24px;
        // font-weight: bold;
      }
      .right {
        flex: 1;
        text-align: right;
        margin-right: 10px;
      }
      .center {
        flex: 1;
        .el-input {
          width: 300px;
        }
      }
      .today-btn {
        margin-right: 16px;
      }
    }
    ::v-deep .fc {
      flex: 1;
      .fc-col-header-cell-cushion {
        display: block;
        font-size: 13px !important;
      }
      .fc-timegrid-col-events {
        z-index: 5;
      }
      .fc-header-toolbar {
        display: none;
      }
      // 日视图和周视图 时间轴第一个时间点不显示
      .fc-timeGridDay-view,
      .fc-timeGridWeek-view,
      .fc-resourceTimeGridDay-view {
        .fc-timegrid-slots > table > tbody > tr:first-child > td:first-child {
          display: none;
        }
        .event-cls,
        .fc-event-title-container {
          margin: 4px 0 0 4px;
        }
      }
      // 日历顶部
      .fc-col-header-cell {
        // background-color: $color-primary!important;
        // color: #fff!important;
        font-weight: 400;
        color: #595959;
        border: none;
      }
      // 日历背景
      .fc-daygrid-day-frame {
        background: #fff;
        .banci {
          position: absolute;
          right: 0;
          top: 4px;
        }
      }
      // 当天日历背景
      // .fc-day-today{
      //   .fc-daygrid-day-frame{
      //     background: #b3d8ff;
      //   }
      // }
      // 日视图左边时间
      .fc-timegrid-slot-label {
        vertical-align: top;
        line-height: 0.1em;
        border: none;
      }
      // 去掉日视图的虚线
      .fc-timegrid-slot-minor {
        border-top-style: none;
      }
      // 事件背景
      .fc-timeGridDay-view,
      .fc-dayGridMonth-view,
      .fc-resourceTimeGridDay-view {
        .fc-timegrid-slots {
          background: #fff !important;
        }
      }
      // 时间间隔高度
      .fc-timegrid-slot {
        height: 2em;
        border-left: none;
        border-right: none;
      }
      // 当前时间线
      .fc-timegrid-now-indicator-arrow {
        border-width: 4px !important;
        border-top-color: #ff4d4f;
        border-bottom-color: #ff4d4f;
        width: 8px;
        height: 8px;
        border-radius: 4px;
      }
      .fc-timegrid-now-indicator-arrow {
        margin-top: -4px;
      }
      .fc-timegrid-slot-label-cushio {
        font-size: 12px;
      }
      .event-cls,
      .fc-event-title-container {
        .fc-event-title {
          /*display: flex;
          height: 100%;*/
          align-items: center;
          // min-height: 2em!important;
          font-weight: 400;
          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;
          color: #595959 !important;
          img {
            width: 24px;
            height: 24px;
            border-radius: 50%;
            margin: 0 2px;
            object-fit: cover;
          }
        }
      }
      .event-cancle {
        // text-decoration: line-through;
        div {
          text-decoration: line-through;
        }
      }
      // 工单日程
      .event-cls-task {
        background: #e6fffb !important;
        &:active {
          color: #fff;
          background: $color-primary-light-6 !important;
        }
        .fc-daygrid-event-dot {
          border: 3px solid $color-primary-light-6 !important;
          border-color: $color-primary-light-6 !important;
          margin: 0 4px 0 2px;
        }
      }
      .event-cls-through {
        text-decoration: line-through;

        .fc-event-title,
        div {
          text-decoration: line-through;
        }
      }
      // 事件日程
      .event-cls-event {
        background: #fffbe6 !important;
        &:active {
          color: #fff !important;
          background: #faad14 !important;
        }
        .fc-daygrid-event-dot {
          border: 3px solid #faae14 !important;
          border-color: #faae14 !important;
          margin: 0 4px 0 2px;
        }
      }
      // 通用日程
      .event-cls-common {
        background: #f6ffed !important;
        &:active {
          color: #fff;
          background: #52c41a !important;
        }
        .fc-daygrid-event-dot {
          border: 3px solid rgb(76, 175, 80) !important;
          border-color: rgb(76, 175, 80) !important;
          margin: 0 4px 0 2px;
        }
      }

      .title-cell-shaded-shadow {
        position: relative;
        &::before {
          content: '';
          width: 100%;
          position: absolute;
          top: 0;
          left: 0;
          border-bottom: 1px solid #e9e9e9;
          box-shadow: 0 3px 6px rgba(0, 0, 0, 0.6);
          z-index: 99;
          opacity: 0.5;
        }
      }

      .fc-scrollgrid-section {
        height: 0;
      }

      // todo 日视图事件宽度不能撑满？
      ::v-deep .fc-day {
        .fc-direction-ltr .fc-timegrid-col-events {
          margin-right: 0;
        }
      }

      // 日视图和周视图
      .fc-timeGridDay-view,
      .fc-timeGridWeek-view,
      .fc-resourceTimeGridDay-view {
        // 事件样式
        .event-cls {
          // background: #fff!important;
          border: none !important;
          &:hover {
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12),
              0 0 6px rgba(0, 0, 0, 0.04);
          }
          .fc-event-main {
            min-height: 1em;
            color: #595959 !important;
            .fc-event-time {
              // 去掉事件的时间显示
              display: none !important;
            }
          }
        }
        .event-cls-task::before {
          content: '';
          position: absolute;
          top: 1px;
          left: -3px;
          width: 4px;
          height: 100%;
          border-radius: 2px;
          background: $color-primary-light-6 !important;
        }
        .event-cls-event::before {
          content: '';
          position: absolute;
          top: 1px;
          left: -3px;
          width: 4px;
          height: 100%;
          border-radius: 2px;
          background: #faae14 !important;
        }
        .event-cls-common::before {
          content: '';
          position: absolute;
          top: 1px;
          left: -3px;
          width: 4px;
          height: 100%;
          border-radius: 2px;
          background: #4caf50 !important;
        }
      }
      .fc-resourceTimelineDay-view,
      .fc-resourceTimelineWeek-view {
        // 事件样式
        .event-cls {
          // background: #fff!important;
          border: none !important;
          &:hover {
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12),
              0 0 6px rgba(0, 0, 0, 0.04);
          }
          .fc-event-main {
            min-height: 1em;
            color: #595959 !important;
            .fc-event-time {
              // 去掉事件的时间显示
              display: none !important;
            }
            .fc-event-title {
              padding-left: 8px !important;
            }
          }
        }
        .event-cls-task .fc-sticky::before {
          content: '';
          position: absolute;
          top: 0;
          left: 0;
          width: 4px;
          height: 100%;
          border-radius: 2px;
          background: $color-primary-light-6 !important;
        }
        .event-cls-event .fc-sticky::before {
          content: '';
          position: absolute;
          top: 0;
          left: 0;
          width: 4px;
          height: 100%;
          border-radius: 2px;
          background: #faae14 !important;
        }
        .event-cls-common .fc-sticky::before {
          content: '';
          position: absolute;
          top: 0;
          left: 0;
          width: 4px;
          height: 100%;
          border-radius: 2px;
          background: #4caf50 !important;
        }
        // 取消的删除线
        .event-cancle div {
          text-decoration: line-through;
        }
      }
      // 月视图
      .fc-dayGridMonth-view {
        .event-cls {
          .fc-daygrid-dot-event .fc-event-title {
            font-weight: 400;
            @include text-ellipsis();
          }
        }
      }

      .current-month-day {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 24px;
        height: 24px;
        border-radius: 50%;
        font-size: 14px;
        background: $color-primary-light-6;
        color: #fff;
      }
      .fc-resourceTimelineDay-view {
        .fc-timeline-header
          > table
          > tbody
          > tr:first-child
          > th:first-child
          > div {
          display: none;
        }
      }
      .fc-resourceTimelineWeek-view {
        .fc-slot-today {
          // 当前时间的阴影
          background: #eee;
          border-color: #fff;
          opacity: 0.5;
        }
      }
      .fc-resource-timeline {
        .fc-scrollgrid-section-body table {
          border-bottom-style: none;
        }
        .fc-scrollgrid-liquid {
          border-collapse: collapse;
        }
        .fc-scrollgrid-section-header {
          border-bottom: 1px solid #eeeeee;
          .fc-day-today .fc-timeline-slot-cushion {
            color: $color-primary-light-6;
          }
        }
        .fc-datagrid-cell-cushion {
          padding: 8px 4px 8px 0;
          position: relative;
          overflow: visible;
        }
        .fc-timeline-events {
          padding-bottom: 0;
        }
        .fc-timeline-more-link {
          background: none;
          div:first-child {
            width: 20px;
            left: 0;
            right: 0;
            position: sticky;
          }
          .fc-timeline-more-link-inner {
            display: none;
          }
        }
        .team-people-resourse {
          display: flex;
          margin-right: 4px;
          .team-people-name {
            flex-grow: 1;
            margin-right: 4px;
            display: flex;
            .team-people-head {
              width: 24px;
              height: 24px;
              border-radius: 50%;
              margin-right: 4px;
              object-fit: cover;
            }
            span {
              width: 65px;
              height: 20px;
              font-size: 12px;
              font-family: PingFangSC-Regular, PingFang SC;
              font-weight: 400;
              color: #595959;
              line-height: 20px;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
              display: inline-block;
            }
          }
          .team-people-icon {
            display: none;
          }
          .el-tooltip__popper.is-dark.none {
            display: none;
            transform-origin: center bottom;
            z-index: 2019;
            position: absolute;
            top: -32px;
          }
          .zhiding {
            .el-tooltip__popper.is-dark.none {
              left: 45px;
              .popper__arrow {
                left: 27px;
              }
            }
            &:hover {
              .el-tooltip__popper.is-dark.none {
                display: block;
              }
            }
          }
          .shanchu {
            .el-tooltip__popper.is-dark.none {
              left: 57px;
              .popper__arrow {
                left: 29px;
              }
            }
            &:hover {
              .el-tooltip__popper.is-dark.none {
                display: block;
              }
            }
          }
          .fanzhuan.shanchu {
            .el-tooltip__popper.is-dark.none {
              left: 57px;
              top: 32px;
              .popper__arrow {
                left: 27px;
                top: -6px;
                transform: rotate(180deg);
                -ms-transform: rotate(180deg); /* Internet Explorer */
                -moz-transform: rotate(180deg); /* Firefox */
                -webkit-transform: rotate(180deg); /* Safari 和 Chrome */
                -o-transform: rotate(180deg); /* Opera */
              }
            }
          }
          i {
            font-size: 14px;
            color: #000000;
          }
          i:hover {
            cursor: pointer;
          }
          .team-top-inner-triangle {
            top: 0;
            border-left: 10px solid transparent;
            border-right: 10px solid #bae7ff;
            border-bottom: 10px solid transparent;
            height: 0;
            width: 0;
            position: absolute;
            right: 0;
            z-index: 2;
          }
        }
        .team-people-resourse:hover {
          span {
            width: 40px;
          }
          .team-people-icon {
            flex-grow: 0;
            display: block;
          }
        }
      }
    }
    ::v-deep .fc-direction-ltr .fc-timeline-body .fc-timeline-slot {
      border: 0 !important;
      // border: 1px solid #eee;
    }
    ::v-deep .fc-direction-ltr .fc-resourceTimelineDay-view .fc-timeline-body .fc-timeline-slot:hover {
      background: #eee;
      border-color: #fff;
      opacity: 0.5;
    }

    // 团队日历
    ::v-deep .fc-direction-ltr .fc-timeline-event:not(.fc-event-start):before,
    .fc-direction-rtl .fc-timeline-event:not(.fc-event-end):after {
      border: 0 !important;
    }
    ::v-deep .fc-direction-ltr .fc-timeline-event:not(.fc-event-end):after,
    .fc-direction-rtl .fc-timeline-event:not(.fc-event-start):before {
      border: 0 !important;
    }
    ::v-deep .fc .fc-timeline-header-row-chrono .fc-timeline-slot-frame {
      justify-content: center;
    }
  }
  .op {
    cursor: pointer;
    margin-left: 12px;
    line-height: 24px;
    color: #8c8c8c;
    span {
      font-size: 16px;
    }
    &:hover {
      color: $color-primary-light-6;
    }
  }
  .calendar-tag-user {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    justify-content: space-between;
    width: 210px;
    border: 1px solid #e0e1e2;
    border-radius: 4px;
    padding: 5px 10px 1px;
    min-height: 32px;
    line-height: 30px;
    margin-bottom: 20px;
    button {
      position: absolute;
      right: 0;
      height: 30px;
    }
    .placeholder-text {
      color: #b3b7c1;
      font-size: $font-size-base;
    }
    .el-tag {
      width: 47%;
      min-height: 24px;
      padding: 1px 6px;
      display: flex;
      align-items: center;
      margin-bottom: 4px;
      span {
        width: 50%;
        display: inline-block;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        line-height: 18px;
      }
    }

    img {
      width: 18px;
      height: 18px;
      border-radius: 50%;
      margin-right: 3px;
    }
    .button-new-tag {
      position: initial;
      height: 24px;
      width: 47%;
      font-size: 12px;
      padding: 1px 6px !important;
      margin-bottom: 4px;
    }
  }
}
</style>

<style lang="scss">
html,
body {
  height: 100%;
  overflow: hidden;
  padding: 0;
  margin: 0;
}
.base-tooltip-agenda {
  background: #fff !important;
  color: #333;
  padding: 6px 0;
  .base-tooltip-content {
    padding: 5px 30px;
    // border-bottom: 1px solid #eee;
    line-height: 27px;
    font-size: 15px;
    &:hover,
    &:active {
      background: $color-primary-light-1;
      color: $color-primary-light-6;
      cursor: pointer;
    }
  }
}

.fc-timeGridDay-view {
  .fc-timegrid-now-indicator-arrow {
    left: unset;
    right: 0 !important;
  }
  .fc-timegrid-now-indicator-line {
    z-index: 5;
  }
  // 日视图不显示星期几
  .fc-col-header-cell {
    display: none;
  }
}
.fc-timeGridWeek-view {
  .fc-timegrid-now-indicator-arrow {
    display: none;
  }
  .fc-scrollgrid-section-body .fc-day-today {
    background: rgba(238, 238, 238, 0.5);
    border-color: rgba(255, 255, 255, 0.5);
    // opacity: 0.5;
  }
  .fc-timegrid-now-indicator-line {
    border-style: none;
    z-index: 5;
    .fc-timegrid-now-indicator-arrow-main {
      position: absolute;
      z-index: 4;
      left: 0;
      border-width: 4px !important;
      border-top-color: #ff4d4f;
      border-bottom-color: #ff4d4f;
      background: red;
      margin-top: -4px;
      width: 8px;
      height: 8px;
      border-radius: 4px;
    }
    .fc-timegrid-now-indicator-line-main {
      position: absolute;
      z-index: 4;
      left: 0;
      right: 0;
      border-style: solid;
      border-color: red;
      border-color: red;
      border-width: 1px 0 0;
    }
  }
}
.fc .fc-timegrid-slot-label-cushion {
  font-size: 12px;
  color: #8c8c8c;
}
.fc .fc-resourceTimelineDay-view .fc-timeline-slot-cushion {
  font-size: 12px;
  color: #8c8c8c;
  font-weight: 400;
}
.fc .fc-resourceTimelineWeek-view .fc-timeline-slot-cushion {
  font-size: 14px;
  font-weight: 400;
}
.fc-theme-standard .fc-scrollgrid {
  border: none !important;
}
.fc-theme-standard th {
  border: none;
}
.fc-col-header {
  // border-bottom: 1px solid #eee;
  box-shadow: 0px 12px 10px -5px rgba(0, 0, 0, 0.05);
}
.fc-theme-standard td {
  border: 1px solid #eee;
  border-left: none;
  border-right: none;
}
.fc .fc-daygrid-day-top {
  align-items: center;
  justify-content: center;
  flex-direction: row;
}
.fc-event-title {
  @include text-ellipsis;
}
.fc .fc-event-title-container .fc-event-title {
  padding-left: 4px;
}
.fc-daygrid-block-event .fc-event-time {
  font-weight: 400;
}
.fc-h-event .fc-event-main {
  color: #595959 !important;
}
.fc-timegrid-event-harness {
  min-height: 2em;
}
.fc .fc-scroller-liquid-absolute {
  bottom: 4em;
}
.fc-h-event {
  border: none;
}
// 点击更多popover
.fc .fc-popover {
  top: 25% !important;
  left: 35% !important;
}
.fc .fc-popover-body {
  max-height: 300px;
  overflow: auto;
  .fc-more-popover-misc {
    height: 30px;
    font-size: 18px;
  }
  .fc-daygrid-event-harness a {
    height: 24px;
    line-height: 24px;
  }
  .fc-event-title {
    width: 300px;
  }
}
.fc .fc-more-popover .fc-popover-header {
  background: #fafafa;
}
// 周视图下面添加阴影
.fc .fc-scroller-harness {
  // box-shadow: 0px 12px 10px -5px rgba(0, 0, 0, 0.05);
}

.fc .fc-day-today .fc-popover-body {
  .fc-more-popover-misc {
    display: flex;
    font-size: 12px;
    color: #8c8c8c;
  }
}

.fc .fc-timeGridWeek-view .fc-scrollgrid-section-header {
  .fc-col-header-cell.fc-day-today {
    color: $color-primary-light-6;
  }
}

.create-agenda-menu {
  margin-top: 5px;
  .el-dropdown-menu__item {
    &:hover,
    &:active {
      background: $color-primary-light-1;
      color: $color-primary-light-6;
    }
  }
  .popper__arrow {
    display: none;
  }
}

.fc .fc-timegrid-event.fc-event-mirror {
  opacity: 0.7;
}

.fc .fc-daygrid-bg-harness .fc-highlight {
  background: $color-primary-light-6;
  opacity: 0.7;
  z-index: 10;
}

.create-agenda-menu {
  .el-dropdown-menu__item:focus,
  .el-dropdown-menu__item:not(.is-disabled):hover {
    color: $color-primary-light-6;
  }
}

.fc-scrollgrid-sync-table {
  // min-height: 450px;
}
.fc-resourceTimeGridDay-view {
  .fc-timegrid-now-indicator-arrow {
    left: unset;
    right: 0 !important;
  }
}
.fc-resourceTimelineWeek-view,
.fc-resourceTimelineDay-view {
  .fc-timeline-now-indicator-arrow {
    top: unset;
    bottom: 0 !important;
    position: absolute;
    z-index: 4;
    left: 0;
    border-width: 4px !important;
    border-top-color: #ff4d4f;
    border-bottom-color: #ff4d4f;
    background: red;
    margin-left: -5px;
    width: 8px;
    height: 8px;
    border-radius: 4px;
  }
  .fc-scroller-harness-liquid table {
    border-right: 1px solid #e8e8e8;
  }
  .fc-resource-timeline-divider {
    width: 0;
  }
}
.fc-dot-pa {
  display: flex;
  align-items: center;
  margin-left: 2px;
}
.el-dialog__body {
  padding: 20px 20px 30px;
}
.planningTimePop {
  .pop_main {
    line-height: 24px;
    > div:nth-child(1) {
      margin-bottom: 20px;
    }
    > div:nth-child(2) {
      margin-bottom: 15px;
    }
    a {
      color: $color-primary;
      text-decoration: underline;
    }
    p {
      margin: 0;
    }
    i {
      font-style: normal;
      color: $color-warning;
    }
  }
}
.checkbox-group-box {
  position: relative;
  .checkbox-type-txt {
    > div {
      position: absolute;
      left: 76px;
      font-size: 12px;
      color: $color-warning;
      a {
        color: $color-warning;
        text-decoration: underline;
      }
    }
    > div:nth-child(1) {
      top: 33px;
    }
    > div:nth-child(2) {
      top: 65px;
    }
  }
}
::v-deep .fc-license-message {
  display: none;
}

.fc .fc-daygrid-body-natural .fc-daygrid-day-events {
  margin-bottom: 0;
}
</style>
